AFNetworking处理请求线程中的成功

时间:2014-01-28 20:46:25

标签: grand-central-dispatch afnetworking-2

我正在使用AFNetworking来获取JSON数据。

我使用的是基本风格:

 NSURL *url = [NSURL URLWithString:serverPath];
 NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

 ... Set custom stuff in header ...
 [request setHTTPMethod:@"POST"];
 ... setup post data ...      

 AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation1, id responseObject) {
    id jsonResponse = [self parseJsonResult:responseObject];
    // Potentially long running operation
    [handler onSuccess:jsonResponse];

} failure:^(AFHTTPRequestOperation *operation1, NSError *error) {
    NSInteger httpStatus = [[operation1 response] statusCode];
    // Do some error handling

}

一些JSON响应需要花费大量时间来处理。这导致一些UI阻塞。所以现在我想将响应处理从主线程移开。是否有一种简单的方法可以在传输线程而不是主线程中执行成功和失败调用?

我打算将它们包装在自己的调度组调度队列中,但我不希望在我还在的时候发生任何其他排队的网络请求解析/处理当前的响应。

在我开始浏览库代码之前,我想过会问。

1 个答案:

答案 0 :(得分:0)

最简单的方法是不使用AFNetworking进行长时间运行的响应处理。我决定只使用

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^ {
       [self processRequestsSycnrounously]

});

并使用以下内容同步驱动我自己的请求队列:

NSData* result = [NSURLConnection sendSynchronousRequest:request  returningResponse:&response error:&error];

而不是使用:

[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation1, id responseObject)
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation1, id responseObject) {
    id jsonResponse = [self parseJsonResult:responseObject];
    [handler onSuccess:jsonResponse];
} failure:^(AFHTTPRequestOperation *operation1, NSError *error) {
    ... blah blah blah
}

这正是我需要做的,并且很容易使用我已经从AFNetworking代码中获得的成功和失败块。