我正在使用 AFNetworking
。我创建了一个名为 MyRequest
的类,它扩展了 NSObject
。我创建了一个名为 requestForPost
的方法
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": variable1};
[manager POST:@"http://app.com/resources" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
当我要调用一个webservice
时,我将参数字典传递给上面的方法,这样它就会执行webservice
。
如何,我想知道 webservice
请求是成功还是失败。我应该如何将结果传递回我在上面调用的 webservice
的 ViewController
。
最佳答案
使用与 AFNetworking 相同的方式:使用 block 。一为成功,一为失败。在您的 UIViewController
中使用这种方式,您将知道您的请求是成功还是失败,以及返回的对象。
在您的 API 文件中:
- (void)yourAPIMethodWithSuccess:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = @{@"foo": variable1};
[manager POST:@"http://app.com/resources" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"JSON: %@", responseObject);
success(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
failure(error);
}];
}
在你的 Controller 中:
- (void)fetchDataForRequest{
YourAPIInstance yourAPIMethodWithSuccess:^(id expectedObject) {
NSLog(@"Success: %@", expectedObject);
} failure:^(NSError *error) {
NSLog(@"Request failed: %@", [error localizedDescription]);
}];
}
关于ios - 我如何知道在 AFNetworking 中是否执行了成功或失败 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29342262/