【发布时间】:2015-09-20 06:07:11
【问题描述】:
NSURLSession 委托方法 URLSessionDidFinishEventsForBackgroundURLSession 没有调用?
我已经在项目功能设置中启用了后台模式。
这里是代码
AppDelegate.h方法
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (nonatomic, copy) void(^backgroundTransferCompletionHandler)();
@end
AppDelegate.m方法
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
self.backgroundTransferCompletionHandler = completionHandler;
}
ViewController.m方法
- (void)viewDidLoad
{
[super viewDidLoad];
//Urls
[self initializeFileDownloadDataArray];
NSArray *URLs = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];
self.docDirectoryURL = [URLs objectAtIndex:0];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.GACDemo"];
sessionConfiguration.HTTPMaximumConnectionsPerHost = 5;
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration
delegate:self
delegateQueue:nil];
}
NSUrlSession 方法
-(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
// Check if all download tasks have been finished.
[self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([downloadTasks count] == 0) {
if (appDelegate.backgroundTransferCompletionHandler != nil) {
// Copy locally the completion handler.
void(^completionHandler)() = appDelegate.backgroundTransferCompletionHandler;
// Make nil the backgroundTransferCompletionHandler.
appDelegate.backgroundTransferCompletionHandler = nil;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Call the completion handler to tell the system that there are no other background transfers.
completionHandler();
// Show a local notification when all downloads are over.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = @"All files have been downloaded!";
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}];
}
}
}];
}
我可以一一下载所有文件,但是下载完所有文件后,URLSessionDidFinishEventsForBackgroundURLSession方法没有调用。
仅在下载所有文件后,我必须执行一些操作方法。
【问题讨论】:
-
顺便说一句,我觉得
getTasksWithCompletionHandler的使用很奇怪,因为URLSessionDidFinishEvents...只有在任务完成时才会被调用。这对我来说似乎是多余的(尽管可能与您手头的问题无关)。如果这种情况发生,调用handleEventsForBackgroundURLSession,然后调用URLSessionDidFinish...,你就有了一条不调用completionHandler的路径。我认为这条路永远不会实现,但如果实现了,你就会引入一个新问题。 -
其实这是我第一次使用 NSUrlSession 类。我的实际要求是一旦下载(所有图像)完成,那么只有我可以从文档目录中检索图像并且我可以在 UICollectionVeiw 中显示
-
我正在关注 APPCODA 的本教程。这是链接appcoda.com/background-transfer-service-ios7
-
我看了那个教程,我认为它总体上很好,尽管我不同意
URLSessionDidFinishEventsForBackgroundURLSession的实现,正如我上面提到的。但我认为这不是你的问题。
标签: ios objective-c xcode nsurlsession nsurlsessiondownloadtask