我在我的应用程序中创建了一个APIController,它有几个调用特定api url的方法,并返回一个填充了api调用结果的模型对象。
api适用于json,到目前为止,我的代码如下所示:
//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”调用。所以我改变了我的方法:
- (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调用完成之前返回空模型。我被困住了,不知道如何重构我的设计以使其发挥作用。
//编辑:我不知道知道是否重要,但我后来想要在调用api时显示加载动画。
答案 0 :(得分:2)
- (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
}];