I am using AlamofireImage to display images in a UITableViewCell
typealias boolAndAnyCompletion = (_ success: Bool, _ value: Any?) -> Void
class ImageHelper {
func fetchImage(url:String, completion: @escaping boolAndAnyCompletion) {
Alamofire.request(url).responseImage { response in
if let image = response.result.value {
completion(true, image)
} else {
completion(false, "No image")
}
}
}
}
This is mostly working fine. I am taking a url from a JSON object and attempted to fetch image at the url. Mostly this works fine and either returns image as expected or fails if the url string is 404 or otherwise invalid.
However today I started getting my app crashing with
libc++abi.dylib: terminating with uncaught exception of type NSException
I narrowed this down to the above method where my JSON response was giving me a url in error that was not pointing to an image.
if if the url I got for an image was "https://bbc.co.uk/news/" that that causes the crash. However if I search for an image at "https://www.google.co.uk/maps/" that fails as expected without crashed and dealt with by error handling.
I know that the best solution is for only correct image urls to be put in JSON but were dealing with humans doing that and mistakes may happen. So, Is there a reason one would 'fail correctly' which the other crashed my app? How can I prevent this crash on some invalid urls?
I found the solution to my problem and not surprised I got no answer as the problem wasn't above. I look at previous answer here and set an exception break point.
My app is also using Realm (which didn't seem relevant at first). I was populating UITableViewCell with data from Realm. Then I downloaded JSON and created new objects and deleted old realm ones.
The exception break point then stopped on
@throw RLMException(@"Object has been deleted or invalidated.")
In the cocoapod. As I was saving a string or the url and not the url in realm I'm guessing the cell started download, was then invalidated and assuming thats what caused the crash.