我想使用 AFNetworking 和这个 AFHTTPClient 子类实现来自 Web 服务的多个 Json 请求以创建表视图。我将在 MainViewController 中创建 tableView。
#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 中接收数据,以便我可以管理这些数据并将其设置在 tableView 中。
-(void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock
completionBlock:(void (^)(NSArray *operations))completionBlock;
谢谢你。