我目前正在开发iOS应用程序,并且我使用AFNetworking与远程API进行通信。我想做的是制作不同的函数,让我返回API响应。我目前的代码是:
-(void)requestMethod:(NSString *)method arguments:(id)arguments
{
NSDictionary *parameters=@{@"jsonrpc": @"2.0", @"method": method, @"params": arguments};
[httpClient postPath:methodPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
NSDictionary *responseParsed=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
}
现在这个代码由块执行,当我从服务器收到响应时调用这些块。什么是函数的最佳实现,当在任何线程上调用时会返回某个方法的响应?像:
-(NSArray *)getUsersFromAPI;
谢谢!
答案 0 :(得分:1)
您可以使用生成的NSArray作为参数来使用方法块,并将其作为arg传递给提取函数:
-(void)getUsersFromAPIWithResponse:(void(^)(AFHTTPRequestOperation *operation, NSArray *users))responseBlock {
NSDictionary *parameters=@{};
[httpClient postPath:methodPath parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
NSArray *responseParsed = //do something cool;
responseBlock(operation, responseParsed);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"%@",error);
}];
}