当应用程序收到推送通知时,我已启用具有远程通知任务的后台模式以在后台下载一个小文件 (100kb)。我已经使用
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
我尝试在 5 分钟后插入带有UILocalNotification
(显示为“现在”)的调试行,[self.downloadTask resume]
但在 5 分钟后被调用,并说self.downloadTask.state
“已暂停”
这种奇怪的行为是什么引起的?