我们的应用使用didReceiveRemoteNotification: fetchCompletionHandler:
方法UIApplicationDelegate
在收到content-available
推送通知时开始下载。
应用程序采取的各个步骤:
[1]收到通知
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
NSLog(@"Remote download push notification received");
[AFHTTPSessionManager_Instance downloadFile:completionHandler];
}
[2]开始新的下载任务
- (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]处理下载
[self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
NSLog(@"Download complete!");
// ... Create save path
return path;
}];
这会产生如下日志:
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!
但有时(完全随机)我看到这样的日志:
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!
换句话说,下载永远不会完成,看起来应用程序会冻结其后台会话。因为当我将应用程序放回到前台时,下载将在某个时刻完成。
之前有没有人见过这种行为? 仅供参考:我启用了正确的功能,使用了正确的配置文件,应用程序有权在后台运行。
更新 我们在开发后台管理器时使用AFNetworking 2.0 and background transfers中的答案/评论
答案 0 :(得分:1)
您在开始下载时调用完成处理程序!我非常确定你应该在下载完成后调用完成处理程序,而不是在下载开始后2秒!换句话说,你应该在completionHandler(UIBackgroundFetchResultNewData);
内调用self setDownloadTaskDidFinishDownloadingBlock...
,并且corse以某种方式传递CompletionBlock。
[self setDownloadTaskDidFinishDownloadingBlock:^NSURL *(NSURLSession *session, NSURLSessionDownloadTask *downloadTask, NSURL *location) {
NSLog(@"Download complete!");
// ... Create save path
NSLog(@"Completion handler!");
completionHandler(UIBackgroundFetchResultNewData);
return path;
}];
正确的日志应该是这样的:
2015-09-21 15:38:57.145 App [315:20933]远程下载推送 已收到通知
2015-09-21 15:38:57.485 App [315:20933]开始下载 http://domain.com/file.mov
2015-09-21 15:38:59.654 App [315:20933]下载完成!
2015-09-21 15:39:06.315 App [315:20933]完成处理程序!