Vì vậy, tôi tạo tải của tôi trên các chủ đề chínhNSURLSession Chủ đề: Theo dõi download nhiều nền
NSURLRequest *request = [NSURLRequest requestWithURL:download.URL];
NSURLSessionDownloadTask *downloadTask = [self.downloadSession downloadTaskWithRequest:request];
[downloadTask resume];
và thêm các NSManagedContextID liên quan đến việc tải về một NSMutableDictionary, vì vậy tôi có thể lấy nó sau này trong các đại biểu call-lưng
[self.downloads setObject:[download objectID] forKey:[NSNumber numberWithInteger:downloadTask.taskIdentifier]];
My self.downloadSession
trên được cấu hình như thế này
- (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;
}
.210
Vấn đề của tôi là callbacks đại biểu dường như kêu gọi các chủ đề khác nhau
- (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];
}
Vì vậy, khi tôi truy cập self.downloads để có được những ObjectId đúng, tôi thực sự truy cập vào NSMutableDictionary từ một thread khác nhau hơn so với cái nó đã được tạo ra trên, và tôi tin rằng NSMutableDictionary không phải là chủ đề an toàn. Vì vậy, là những gì các giải pháp tốt nhất cho việc này, tôi có thể sử dụng một cái gì đó như thế này
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
khi tuyên bố phiên giao dịch, thiết lập các hàng đợi đại biểu đến mainQueue mà gây ra tất cả các đại biểu được gọi vào các chủ đề chính, nhưng tôi sẽ muốn giữ tất cả các cuộc gọi lại trên một chuỗi nền nếu có thể
Bạn đã thử chỉ cần đặt chuỗi của riêng mình khi xác định phiên? – Mundi
@Mundi Điều gì về việc xử lý với mô hình 'NSMutableArray' và' NSObject' như được giải thích trong [hướng dẫn này?] (Http://www.appcoda.com/background-transfer-service-ios7/) – Praveenkumar