我想从具有AFNetworking和此AFHTTPClient子类的Web服务实现多个Json请求,以创建表View。我将在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;
谢谢。
答案 0 :(得分:0)
依次回答你的问题:
我的第一个问题是,如何从操作NSArray获取数据?
您可以从集合中每个操作的responseJSON
属性中获取此信息:
for (AFJSONRequestOperation *operation in operations) {
id JSON = operation.responseJSON;
}
我的第二个问题是在我的AFHTTClient子类中实现此方法,并使用委托从ViewController调用它,并直接在ViewController中接收数据,以便我可以管理这些数据并在tableView中设置它。
在子类中,使用所需信息创建一个带有回调块参数的新方法,并在批处理完成块的末尾调用该块。