在使用 AFNetworking 库时,我遇到了一个问题,在使用 AFURLSessionManager downloadTaskWithRequest 的目标参数代码块异步将 JSON 数据下载到文件中后,我希望在其 completionHandler 块中异步执行其余操作。问题是 completionHandler 块似乎没有异步运行。
是否需要设置新的会话管理器和/或下载任务来完成此操作。是否有更好的方法来执行此操作,以便可以在 completionHandler 块中远离主线程执行操作。
想要完成此操作的原因是避免占用主线程,以防有大量数据需要分配给 self.googleResults 数组,或者更确切地说是在使用包含特定关键数据属性的自定义类的 for 循环中最终将作为元素添加到数组中。
这是到目前为止的代码......
- (void)viewDidLoad
{
[super viewDidLoad];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURL *url = [NSURL URLWithString:@"https://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)
{
// NOTE: This code block runs asynchronously
NSURL *docPathURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
return [docPathURL URLByAppendingPathComponent:[response suggestedFilename]];
} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)
{
// NOTE: This code block does not run asynchronously
// Would there be a need to create a new session and/or download task here to get the data from the filePath asynchronously?
// Or is there another way to this for the following code?
NSError *jsonSerializationErr;
NSData *jsonData = [NSData dataWithContentsOfURL:filePath];
NSDictionary *reponseDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&jsonSerializationErr];
// self.googleResults is an instance of (NSArray *)
self.googleResults = [[reponseDictionary objectForKey:@"responseData"] objectForKey:@"results"];
NSLog(@"%@", self.googleResults);
}];
[downloadTask resume];
}