2

我正在按照教程学习 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在获得响应后返回响应。我不知道语法。有人可以帮助我吗?

4

2 回答 2

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

希望这可以帮助

于 2013-08-09T12:15:51.767 回答
0

您可以像这样简单地记录它 //success 是

NSLog(@"%@", JSON);

或者,如果您希望它采用字符串格式,则:

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

希望这可以帮助。

于 2013-08-09T12:16:06.277 回答