If you want to perform an operation in the background, then you'll need to wrap it in a background task. It's also very important that you call endBackgroundTask
when you're finished - otherwise the app will be killed after its allotted time has expired.
Something like this should work for you:
Declare a property:
@property(assign, nonatomic) UIBackgroundTaskIdentifier backgroundFetchTask;
Then:
- (void) fetchImageInBackground
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[self beginBackgroundFetchTask];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &error];
// Store your image
[self endBackgroundFetchTask];
});
}
- (void) beginBackgroundFetchTask
{
self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[self endBackgroundFetchTask];
}];
}
- (void) endBackgroundFetchTask
{
[[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
self.backgroundFetchTask = UIBackgroundTaskInvalid;
}