Reputation: 16841
I am working with AFNetworking
. I created a class called MyRequest
which extends NSObject
. I created a method called requestForPost
that
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);
}];
When i am going to call a webservice
, i pass the parameter dictionary to the above method so it'll execute the webservice
.
How, am i suppose to know if the webservice
request was a success or a failure. How am i supposed to pass the result back to the ViewController
that i called the above webservice
.
Upvotes: 1
Views: 852
Reputation: 9354
Create your custom network layer class to interact with server, where you can make custom handling of any request results/errors. And then use this class in your view controllers.
In this case you can change code in one place and can be sure that everything will be changed for all app, where you use this network layer class
Upvotes: 0
Reputation: 3590
Use the same way as AFNetworking do: use blocks. One for the success, one for the failure. Using this way in your UIViewController
, you will know if your request was a success or failure, and the object returned.
In your API file:
- (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);
}];
}
In your controller:
- (void)fetchDataForRequest{
YourAPIInstance yourAPIMethodWithSuccess:^(id expectedObject) {
NSLog(@"Success: %@", expectedObject);
} failure:^(NSError *error) {
NSLog(@"Request failed: %@", [error localizedDescription]);
}];
}
Upvotes: 2