AFURLSessionManager downloadTaskWithRequest completionHandler不是异步的

时间:2014-09-06 01:22:50

标签: ios asynchronous afnetworking completionhandler

在使用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];
}

0 个答案:

没有答案