Crash when creating UIImage from Data

Viewed 441

In my application, I'm attempting to instantiate a UIImage from Data. I've been seeing some crash logs come in from App Store Connect showing that my code is crashing on this particular line:

guard let data = photo.data, let image = UIImage(data: data) else { return nil }

Below is the backtrace. PhotoCache is the last object I have control over, and .imageFor(_:) is the method that the line above is contained in.

 Crash Logs

What is PFEvanscentData, and what might be causing it to crash in this scenario?

Edit: Here is the full method.

private var cache = NSCache<NSString, UIImage>()
    
func imageFor(_ photo: Photo) -> UIImage? {
    guard let key = photo.id as NSString? else { return nil }
    if let image = cache.object(forKey: key) {
        return image
    }
    guard let data = photo.data, let image = UIImage(data: data) else { return nil }
    cache.setObject(image, forKey: key)
    return image
}
3 Answers

The problem might be in memory warnings. NSCache do not guarantee to remove cached images after receiving a memory warning. I would suggest to subclass NSCache and inside subclass listen (using NSNotificationCenter) for didReceiveMemoryWarningNotification and if you get an warning remove elements from cache.

It looks like it might be an issue of using an objective-c class within this swift class. I'm looking at the line

Data._unconditionallyBridgeFromObjectiveC

You probably need to double check that the NSData coming from Objective-C is actually non-nil and is being converted to the correct type that you are sending to the UIImage initializer, since there's nothing that's actively enforcing that on the Obj-C side you should make sure it is correct on the swift side.

Related