shoutuan
shoutuan
2016-02-02 07:10
采纳率: 100%
浏览 2.1k
已采纳

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

学习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条回答 默认 最新

  • IDOshi201109
    狮兄 2016-02-02 08:48
    已采纳

    根据你描述的貌似行不通,毕竟你是异步获取数据,获取完之后,不走你那个NSLog(@"out of winddirection is %@",winddirection);,你可以在block中获取到数据之后进行调用外部方法(在外部方法里面实现NSLog(@"out of winddirection is %@",winddirection);),进行赋值或者刷新UI。

    点赞 评论
  • oyljerry
    oyljerry 2016-02-02 08:13

    在block外面定义变量,然后block中异步获取的数据,给变量赋值,这样外面就可以通过变量来获取取得的数据

    点赞 评论
  • u013371670
    比萨斜人 2019-06-24 08:44
    点赞 评论

相关推荐