在AFNetworking中回调DidReceiveData

时间:2013-03-13 06:32:16

标签: ios objective-c afnetworking

我有一个GET服务调用,我必须在收到响应时执行某些操作。

据我所知,AFNetworking中的委托方法实际上只在请求完成或完全失败时通知。

通过对AFNetworking的深入了解,我发现AFURLConnectionOperation获得了回调

- (void)connection:(NSURLConnection __unused *)connection
didReceiveData:(NSData *)data;

现在,我的问题是,如何在发起请求的类中获得此回调?

P.S。我累了使用NSNotification发送NSNotificationCenter,我收到了通知。但是,由于多个同时发送的请求被发送到服务器,我无法区分哪个请求的响应是我收到通知。

修改

我注意到AFHTTPRequestOperation继承自AFURLConnectionOpertaion所以我可以实现connection:didReceiveData NSURLConnectionDelegate方法,但问题是,如何从那里发送回调。 :(

1 个答案:

答案 0 :(得分:3)

以下是一个完整的示例:

    NSMutableURLRequest *request = [[HTTPClient sharedInstance] requestWithMethod:@"GET" path:iurl parameters:nil];
    AFHTTPRequestOperation *operation = [[HTTPClient sharedInstance] HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"success");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"failure");
    }];
    [operation setDownloadProgressBlock:^( NSUInteger bytesRead , long long totalBytesRead , long long totalBytesExpectedToRead )
     {
         NSLog(@"%lld of %lld", totalBytesRead, totalBytesExpectedToRead);
     }
     ];
    [[HTTPClient sharedInstance] enqueueHTTPRequestOperation:operation];