在AFNETWORKING中返回响应

时间:2013-08-09 12:02:05

标签: ios afnetworking

我正在关注this教程,以便在IOS中学习AfNetworking 我正在使用以下函数从服务器获取响应:

{
    // 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];
}

我想要的是编写一个函数,它会在得到响应之后将响应返回为NSString。我不知道语法。任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:9)

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];

}

调用

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

希望这会有所帮助

答案 1 :(得分:0)

你可以简单地将其记录在//成功

的地方
NSLog(@"%@", JSON);

或者,如果你想要一个字符串格式,那么:

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

希望这有帮助。