Recipe: Simple Downloads

Many classes provide convenience methods that allow you to request data from the Internet, wait until that data is received, and then move on to the next step in the application. The following snippet is both synchronous and blocking:

- (UIImage *)imageFromURLString:(NSString *)urlstring {     // This is a blocking call     return [UIImage imageWithData:[NSData         dataWithContentsOfURL:[NSURL URLWithString:urlstring]]]; }

You will not return from this method until all the data is received. If the connection hangs, so will your app. The iOS system watchdog will summarily terminate your app if it blocks the main thread for too long; it won’t just hang forever.

Do not use such convenience ...

Get The Core iOS Developer’s Cookbook, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.