AFHTTPRequestOperationManager在块中返回数据 [英] AFHTTPRequestOperationManager return data in block
问题描述
我在应用程序中创建了一个APIController,该APIController具有几种方法,这些方法可以调用特定的api URL,并返回填充有api调用结果的模型对象.
I created an APIController in my application that has several methods that call specific api urls and return a model object populated with the result of the api call.
该api可与json一起使用,到目前为止,我的代码如下所示:
The api works with json and up to now my code looks like the following:
//Definition:
- (MyModel *)callXYZ;
- (MyModel *)callABC;
- (MyModel *)call123;
//Implementation of one:
- (MyModel *)callXYZ {
//Build url and call with [NSData dataWithContentsOfURL: url];
//Create model and assign data returned by api
return model;
}
现在,我想使用出色的AFNetworking框架摆脱"dataWithContentsOfURL"调用.所以我改变了我的方法:
Now I want to use the great AFNetworking framework to get rid of that "dataWithContentsOfURL" calls. So I changed my methods:
- (MyModel *)callXYZ {
__block MyModel *m;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//process data and assign to model m
}
return m;
}
该代码将无法工作,因为在url调用完成之前将返回空模型.我被困住了,不知道如何重构我的设计才能使其正常工作.
This code won't work cause the empty model gets returned before the url call has finished. I am stuck and don't know how to refactor my design to get this to work.
//不知道是否重要,但是我稍后想在调用api时显示加载动画.
// I don't know if it is important to know, but I later want to show a loading animation while the api gets called.
推荐答案
- (void)callXYZWithCompletion:(void (^)(MyModel *model))completion {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
MyModel *m;
//process data and assign to model m
if(completion) {
completion(m);
}
}
}
用法示例:
// Start the animation
[self callXYZWithCompletion:^(MyModel *model) {
// Stop the animation
// and use returned model here
}];
这篇关于AFHTTPRequestOperationManager在块中返回数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!