Jeff
Jeff

Reputation: 1403

Returning response in AFNETWORKING

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

{
    // 1
    NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
    NSURL *url = [NSURL URLWithString:weatherUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    // 2
    AFJSONRequestOperation *operation =
    [AFJSONRequestOperation JSONRequestOperationWithRequest:request
        // 3
        success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            //Success
        }
        // 4
        failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Weather"
                                                         message:[NSString stringWithFormat:@"%@",error]
                                                        delegate:nil
                                               cancelButtonTitle:@"OK" otherButtonTitles:nil];
            [av show];
        }];

    // 5
    [operation start];
}

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

Upvotes: 2

Views: 2762

Answers (2)

Pratyusha Terli
Pratyusha Terli

Reputation: 2343

Try this


- (void)getResponse:(void (^)(id result, NSError *error))block {
       NSString *weatherUrl = [NSString stringWithFormat:@"%@weather.php?format=json", BaseURLString];
       NSURL *url = [NSURL URLWithString:weatherUrl];
       NSURLRequest *request = [NSURLRequest requestWithURL:url];

      // 2
      AFJSONRequestOperation *operation =
       [AFJSONRequestOperation JSONRequestOperationWithRequest:request
      // 3
      success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        //Success
                   block(JSON,nil); //call block here
      }
     // 4
     failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON)    {
          UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error Retrieving     Weather"
                                                     message:[NSString stringWithFormat:@"%@",error]
                                                    delegate:nil
                                           cancelButtonTitle:@"OK" otherButtonTitles:nil];
           [av show];
      }];

  // 5
  [operation start];

}

calling

[self getResponse:^(id result, NSError *error) {
         //use result here
 }];

hope this helps

Upvotes: 9

geekchic
geekchic

Reputation: 2431

You could simply log it like this where //success is

NSLog(@"%@", JSON);

Or if you wanted it in a string format then:

[NSString stringWithFormat:@"JSON response is %@", JSON];

Hope this helps.

Upvotes: 0

Related Questions