所以我创建主线程NSURLSession主题:跟踪多个后台下载
NSURLRequest *request = [NSURLRequest requestWithURL:download.URL];
NSURLSessionDownloadTask *downloadTask = [self.downloadSession downloadTaskWithRequest:request];
[downloadTask resume];
我的下载和添加具有下载到一个NSMutableDictionary相关的NSManagedContextID, 这样我就可以在后面的委托检索回调
[self.downloads setObject:[download objectID] forKey:[NSNumber numberWithInteger:downloadTask.taskIdentifier]];
我self.downloadSession
上述配置这样
- (NSURLSession *)backgroundSession
{
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.test.backgroundSession"];
configuration.discretionary = YES;
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
});
return session;
}
我的问题是委托回调似乎在不同的线程
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
NSManagedObjectID *downloadID = [self.downloads objectForKey:[NSNumber numberWithInteger:downloadTask.taskIdentifier]];
double progress = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:downloadID,@"download",[NSNumber numberWithDouble:progress],@"progress", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"DownloadProgress" object:nil userInfo:userInfo];
}
被称为所以,当我访问self.downloads得到正确的objectID,我实际上是从不同的线程比一个访问的NSMutableDictionary它创建于,我相信NSMutableDictionary不是线程安全的。那么,什么是我们的最佳解决方案,我可以宣布会议时使用这样的事情
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
,设置委托队列的mainQueue这导致所有被称为主线程的代表,但我会喜欢在可能的情况下将所有回调保留在后台线程上
您是否尝试过在定义会话时设置自己的线程? – Mundi
@Mundi如何处理'NSMutableArray'和'NSObject'的模型,如[本教程?](http://www.appcoda.com/background-transfer-service-ios7/)所述 – Praveenkumar