Returning response in AFNETWORKING

余生颓废 提交于 2019-12-12 21:36:26

问题


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 ?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/18146215/returning-response-in-afnetworking

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!