显示加载消息,直到完全解析json iOS

时间:2014-05-24 11:30:11

标签: ios json parsing loading

好的,这是一个问题,在我从服务器上完全下载数据之前,如何模拟加载消息。我有这个问题,因为当从下载的json保存数据的属性仍为零时,我无法将数据传递给下一个视图控制器。那么,在完全解析Json之前,我怎样才能模拟加载消息。

这是我获取数据的代码

-(void)fetchFeed
{
NSString *requestString = @"some website";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];

NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    self.locations = jsonObject[@"someKey"];
    NSLog(@"%@", self.locations);
}


];

[dataTask resume];
}




- (void)viewDidLoad
{
[super viewDidLoad];
MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
[self.view addSubview:hud];
[hud show:YES];
[hud setLabelText:@"Loading..."];

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
    [self fetchFeed];   //Network activity
    dispatch_async(dispatch_get_main_queue(), ^{
        //do stuff after json download
        [MBProgressHUD hideHUDForView:self.view animated:YES];
    });
});

1 个答案:

答案 0 :(得分:3)

请查看我的回答here ..你正在寻找同样的事情..

我已经使用MBProgressHUD来显示加载消息。

就像

一样简单
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
        [self.view addSubview:hud];
        [hud show:YES];
        [hud setLabelText:@"Loading..."];

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
        //Network activity
        dispatch_async(dispatch_get_main_queue(), ^{
            //do stuff after json download
            [MBProgressHUD hideHUDForView:self.view animated:YES];
        });
    });

有关更详细的答案,请查看链接。

************* EDIT ******************* 当您使用NSURLSession时,它允许您执行后台下载操作。根据您发布的代码,我们不会使用dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{})

启动新主题

请试试这个..

- (void)viewDidLoad
{
   [super viewDidLoad];
   [self fetchFeed];   //Network activity
}


-(void)fetchFeed
{
    MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:hud];
    [hud show:YES];
    [hud setLabelText:@"Loading..."];

    NSString *requestString = @"some website";
    NSURL *url = [NSURL URLWithString:requestString];
    NSURLRequest *req = [NSURLRequest requestWithURL:url];

    [[self.session dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
        NSDictionary * jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        self.locations = jsonObject[@"someKey"];
        NSLog(@"%@", self.locations);
         dispatch_async(dispatch_get_main_queue(), ^{
             [MBProgressHUD hideHUDForView:self.view animated:YES];
         });
    }] resume];

}

这应该有效。