3
- (NSURLSession *)sharedBackgroundSession
{
    static NSURLSession *sharedBackgroundSession = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.example.apple-samplecode.SimpleBackgroundTransfer.BackgroundSession"];
        configuration.URLCache = [NSURLCache sharedURLCache];
        configuration.requestCachePolicy = NSURLRequestReturnCacheDataElseLoad;
        sharedBackgroundSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    });
    return sharedBackgroundSession;
}

// When executed on simulator, things work as expected, I never get a nil result.
// When executed on iPhone 5s device, nextDownloadTask is always nil
NSURLSessionDownloadTask *nextDownloadTask = [[self sharedBackgroundSession] downloadTaskWithRequest:request];

有任何想法吗?

2014 年 9 月 12 日更新:我又遇到了这个问题,谷歌搜索并找到了这个 SO 帖子,然后看到我是这个问题的作者!这一次-URLSession:task:didCompleteWithError甚至没有被召唤。解决方案是重新启动我的手机。这一定是苹果的错误。我在我的 iPhone 5s 上运行 iOS7。

4

4 回答 4

1

您应该实施URLSession:task:didCompleteWithError:并且它应该报告有意义的错误(如果有)。

对于适用于模拟器而非设备的各种问题,它们包括(a)在 URL 中使用 localhost;(b) 使用仅在 LAN 和 iOS 设备上可用的 URL 无法通过 wifi 成功连接,例如可能仅通过蜂窝连接;等等。您必须分享更多关于您要连接的 URL 类型的信息。

根据文档NSURLErrorDomain错误-999NSURLErrorCancelled. 我不清楚为什么您会在这种情况下收到该特定错误,除非您明确取消请求或使会话无效。

于 2014-03-01T16:27:45.197 回答
0
  1. 需要为您的 NSURLSession 调用 invalidateAndCancel
  2. 设置为 nil 你的 NSURLSession
  3. 再次创建 NSURLSession
  4. 再次创建 NSURLSessionDownloadTask

例如

NSURLSessionDownloadTask *dataTask = [self.yourSession downloadTaskWithRequest:urlRequest];
NSInteger attemptsNumber = 5;
for (NSUInteger attempts = 0; !dataTask && attempts < attemptsNumber; attempts++){
    [self.yourSession invalidateAndCancel];
    self.yourSession = nil;

    NSURLSessionConfiguration *backgroundConfig = [NSURLSessionConfiguration backgroundSessionConfiguration:[[NSBundle mainBundle] bundleIdentifier]];
    self.yourSession = [NSURLSession sessionWithConfiguration:backgroundConfig delegate:self delegateQueue:nil];
    dataTask = [self.yourSession downloadTaskWithRequest:urlRequest];
}
于 2014-10-24T10:02:37.950 回答
0

就我而言,我能够找到解决此问题的方法:

1)调用sharedBackgroundSession函数

2) 在该会话上调用 downloadTaskWithRequest 以测试会话是否正常工作,即返回非零值

3) 如果#2 失败,则延迟后重试:

[_sharedBackgroundSession performSelector:@selector(sharedBackgroundSession) withObject:nil afterDelay:0.01];

就我而言,第一次尝试有时会失败,有时会成功。但第二次尝试似乎可靠地成功了。

于 2014-03-17T22:05:37.543 回答
0

我通过调用解决了这个问题[backgroundSession invalidateAndCancel]。我只需要调用一次,然后我删除了代码。

我现在想知道是否应该检测何时无法再创建invalidateAndCancel任务并在尝试其他任务之前调用。

于 2014-05-09T20:36:56.227 回答