pipe理enqueueBatchOfHTTPRequestOperationsWithRequests AFHTTPClient子类

我想要实现来自Web服务的AFNetworking和这个AFHTTPClient子类的多个Json请求来创build一个表视图。 我将在MainViewController中创buildtableView。

#import "AFHTTPClient.h" @interface YlyHTTPClient : AFHTTPClient + ( YlyHTTPClient *)sharedHTTPClient; - (id)initWithBaseURL:(NSURL *)url; @end #import "YlyHTTPClient.h" static NSString * const urlString = @"http://localhost/example/"; @implementation YplyHTTPClient + (YlyHTTPClient *)sharedHTTPClient { static YeeplyHTTPClient *_httpClient = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _httpClient = [[YlyHTTPClient alloc] initWithBaseURL:[NSURL URLWithString:urlString]]; [_httpClient setParameterEncoding:AFJSONParameterEncoding]; [_httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]]; }); return _httpClient; } -(id)initWithBaseURL:(NSURL *)url { self = [super initWithBaseURL:url]; if (!self) { return nil; } [self registerHTTPOperationClass:[AFJSONRequestOperation class]]; [self setDefaultHeader:@"Accept" value:@"application/json"]; return self; } 

首先,我试着从MainViewController调用enqueueBatchOfHTTPRequestOperationsWithRequest方法来做到这一点:

  - (void)viewDidLoad { NSMutableArray *mutableRequests = [NSMutableArray array]; for (NSString *URLString in [NSArray arrayWithObjects:@"users", @"projects", @"interestedUsers", nil]) { [mutableRequests addObject:[[YlyHTTPClient sharedHTTPClient] requestWithMethod:@"GET" path:URLString parameters:nil]]; } [[YlyHTTPClient sharedHTTPClient] enqueueBatchOfHTTPRequestOperationsWithRequests:mutableRequests progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations) { NSLog(@"%lu of %lu Completed", (unsigned long)numberOfCompletedOperations, (unsigned long)totalNumberOfOperations); } completionBlock:^(NSArray *operations) { NSLog(@"Completion: %@", [operations objectAtIndex:1]); }]; [super viewDidLoad]; } 

而我从NSLog得到的输出是:

  Completion: <AFJSONRequestOperation: 0x75dbe60, state: isFinished, cancelled: NO request: <NSMutableURLRequest http://localhost/yeeply_service/api/example/projects>, response: <NSHTTPURLResponse: 0x72cd000>> 

(我有三个NSMutableRequest,但我只在这里显示一个)。

我的第一个问题是,我如何从操作NSArray中获取数据? NSArray中没有JSON响应的信息吗? 如果有的话,我怎样才能把它作为字典来阅读?

我的第二个问题是关于在我的AFHTTClient子类中实现此方法,并使用委托从ViewController中调用它,并直接在ViewController中接收数据,以便我可以pipe理这些数据并将其设置在tableView中。

 -(void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock completionBlock:(void (^)(NSArray *operations))completionBlock; 

谢谢。

依次回答你的问题:

我的第一个问题是,我如何从操作NSArray中获取数据?

您可以从集合中的每个操作的responseJSON属性中获取此信息:

 for (AFJSONRequestOperation *operation in operations) { id JSON = operation.responseJSON; } 

我的第二个问题是关于在我的AFHTTClient子类中实现此方法,并使用委托从ViewController中调用它,并直接在ViewController中接收数据,以便我可以pipe理这些数据并将其设置在tableView中。

在你的子类中,用你需要的信息创build一个带有callback块参数的新方法,并在批量结束块的末尾调用该块。