How to get response value from NSObject class through AFNetworking?

439 views Asked by At

I am following this tutorial to learn AfNetworking in IOS And I am using the following function to get the response from the server:

For example, I have one method which returns a value:

{
    __block id response = [[NSDictionary alloc]init];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        response=responseObject;
        NSLog(@"JSON: %@", response);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];

    NSLog(@" return Dic ==> %@",response);
    return response;
}

What I want is to write a function which will returns the response as a NSDictionary after getting response. I don't know the syntax.Can anybody help me ?

2

There are 2 answers

0
cbiggin On

Sure... you probably don't need to declare the NSDictionary as a block object though:

{
    if ([responseObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *response = (NSDictionary *)responseObject;
        ...
    }
}
0
hgwhittle On

Returning the response outside of the success block will only contain the blank NSDictionary object you initialized. Your encapsulating method could have a block as a parameter to be executed when you receive the response.

-(void)makeServiceCallSuccess:(void (^)(NSDictionary *response))success
           failure:(void (^)(NSError *error))failure {

    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        response = (NSDictionary *)responseObject;
        success(response);
        NSLog(@"JSON: %@", response);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        failure(error);
        NSLog(@"Error: %@", error);
    }];
}

Then you'll call the method like this:

[YourClass makeServiceCallSuccess:^(NSDictionary *response) {

    //Do stuff with 'response'

} failure:^(NSError *error) {
    //Do stuff with 'error'
}];