shoutuan
shoutuan
2016-02-02 07:10

IOS中如何获取AFNetworking中GET或POST的数据

  • ios

学习AFnetworking时遇到数据的获取问题:
在GET函数体内能成功获取到正确数据,而函数外为null,我想应该是异步问题,那么,如何在函数(block)外面获取到正确的数据呢?

http://localhost/json/1.json 的内容如下:

 { 
"tempMinC": "11",
"tempMinF": "51",
 "weatherCode": "113",
"winddirection": "WNW"
}

代码为:

#import "AFHTTPRequestOperationManager.h"

 @interface ViewController ()
{
    __block NSString *winddirection;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
   [super viewDidLoad];
   NSString *url = @"http://localhost/json/1.json";

   AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
   [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
   winddirection = [(NSDictionary *)responseObject objectForKey:@"winddirection"];
   NSLog(@"winddirection is %@",winddirection);
   } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
   NSLog(@"Error...%@",error);
  }];
   NSLog(@"out of winddirection is %@",winddirection);
}

执行结果为:

2016-02-02 22:03:39.292 1[1042:60b] out of winddirection is (null)
2016-02-02 22:03:39.419 1[1042:60b] winddirection is WNW

如何在NSLog(@"out of winddirection is %@",winddirection);的地方获取到正确的数据呢?

  • 点赞
  • 回答
  • 收藏
  • 复制链接分享

3条回答

为你推荐

换一换