我已使用配置下载会话
NSURLSessionConfiguration *backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionIdentifier]; [backgroundConfiguration setAllowsCellularaccess:YES]; self.backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
并使用它激活它
NSMutableuRLRequest *request = [NSMutableuRLRequest requestWithURL:[hostComponents URL]]; [request setAllowsCellularaccess:YES]; NSMutableData *bodyMutableData = [NSMutableData data]; [bodyMutableData appendData:[params dataUsingEncoding:NSUTF8StringEncoding]]; [request setHTTPMethod:@"POST"]; [request setHTTPBody:[bodyMutableData copy]]; _downloadTask = [self.backgroundSession downloadTaskWithRequest:request]; [self.downloadTask resume];
现在一切都可以正常工作,只有当我通过Wifi连接或超过蜂窝,但iPhone连接到xCode的电缆,如果我断开iPhone,并通过蜂窝接收推送通知代码停止在[self.downloadTask resume];线不调用URL.
处理这些操作的类是NSURLSessionDataDelegate,NSURLSessionDownloadDelegate,NSURLSessionTaskDelegate等实现:
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengedisposition,NSURLCredential *))completionHandler - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
我尝试在[self.downloadTask resume]之后插入一个UIlocalnotification(现在显示为’Now)的调试行,但在5分钟后调用,并指出self.downloadTask.state被“暂停”
什么是这个奇怪的行为?
解决方法
https://developer.apple.com/Library/ios/documentation/Foundation/Reference/NSURLSessionConfiguration_class/Reference/Reference.html#//apple_ref/occ/instp/NSURLSessionConfiguration/discretionary
说:自由财产:
discussion
When this flag is set,transfers are more likely to occur when plugged
into power and on Wi-Fi. This value is false by default.This property is used only if a session’s configuration object was
originally constructed by calling the backgroundSessionConfiguration:
method,and only for tasks started while the app is in the foreground.
If a task is started while the app is in the background,that task is
treated as though discretionary were true,regardless of the actual
value of this property. For sessions created based on other
configurations,this property is ignored.
这似乎意味着如果下载在后台启动,操作系统总是有权决定是否和何时进行下载.在完成这些任务之前,操作系统总是等待WiFi连接.
我的经验支持这个猜想.我发现,当设备处于蜂窝状态时,我可以发送几个下载通知.他们仍然卡住当我将设备切换到wifi时,他们都会通过.