Our app utilizes didReceiveRemoteNotification: fetchCompletionHandler:
methods UIApplicationDelegate
to start a download when a content-available
push notification is received.
The individual steps the app takes:
[1] Receive a notification
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
NSLog(@"Remote download push notification received");
[AFHTTPSessionManager_Instance downloadFile:completionHandler];
}
[2] Start a new download Task
- (void)downloadFile:(void (^)(UIBackgroundFetchResult))completionHandler {
NSURLSessionDownloadTask *task = [AFHTTPSessionManager_Instance downloadTaskWithRequest:request progress:nil destination:nil completionHandler:nil];
[task resume];
NSLog(@"Starting download of %@", request.URL.absoluteString);
// Some additional time to start the download
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
NSLog(@"Completion handler!");
completionHandler(UIBackgroundFetchResultNewData);
});
[3] Handle the download
[self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
NSLog(@"Download complete!");
// ... Create save path
return path;
}];
This results in a log like this:
2015-09-21 15:38:57.145 App[315:20933] Remote download push notification received
2015-09-21 15:38:57.485 App[315:20933] Starting download of http://domain.com/file.mov
2015-09-21 15:38:59.654 App[315:20933] Completion handler!
2015-09-21 15:39:06.315 App[315:20933] Download complete!
But sometimes (completely random) I see logs like this:
2015-09-21 15:38:57.145 App[315:20933] Remote download push notification received
2015-09-21 15:38:57.485 App[315:20933] Starting download of http://domain.com/file.mov
2015-09-21 15:38:59.654 App[315:20933] Completion handler!
In other words the download never completes, it looks like the app freezes its background session. Because when I put the app back into the foreground the download will finish at some point.
Has anyone seen this behavior before?
FYI: I enabled the right capabilities, used a correct provision profile and the app has permissions to run in the background.
Update: We've used answers/comments in AFNetworking 2.0 and background transfers when developing the background manager