HUD无法在iOS中运行

时间:2014-07-28 08:56:31

标签: ios objective-c mbprogresshud

我需要从JSON对象加载一些图像。加载这些图像时,我需要在我的视图上显示HUD。我试着定义一个如下的HUD,

在viewDidLoad方法中定义HUD

MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = @"Loading Images";
[hud show:YES];
[hud showWhileExecuting:@selector(loadJSONData) onTarget:self withObject:nil animated:YES];

loadJSONData方法

-(void)loadJSONData{
   _myObject = [[NSMutableArray alloc] init];

   NSData *jsonSource = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

   id jsonObjects = [NSJSONSerialization JSONObjectWithData:
                  jsonSource options:NSJSONReadingMutableContainers error:nil];
   NSArray *dataDic = [jsonObjects objectForKey:@"data"];
   for (NSDictionary *dicData in dataDic) {
      Lawyer *l = [[Lawyer alloc] init];
      dispatch_async(queue, ^{
         NSString *imgUrl = [NSString stringWithFormat:@"myurl",l.imageUrl];
         NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imgUrl]];
         UIImage *image = [UIImage imageWithData:data];
         dispatch_async(dispatch_get_main_queue(), ^{
           l.uiImage = image;
        });

     });
   [_myObject addObject:[l initFromDictionary:dicData]];
   }
}

我的输出显示HUD一秒钟然后消失了。没有数据正在加载。我该如何解决这个问题。

提前致谢!

2 个答案:

答案 0 :(得分:1)

使用此代码:

MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView: self.view];
[self.view addSubview: hud];
hud.labelText = @"Loading Images...";

[hud showAnimated:YES whileExecutingBlock:^{
    [self loadJSONData];
} completionBlock:^{
    // Refresh UI 
}];

但请确保,whileExecutingBlock使用线程,您必须在主线程上进行所有UI更改。

答案 1 :(得分:0)

您的代码按预期工作。 loadJSONData执行异步请求,因此选择器实际上已完成执行。你应该做的是在方法loadJSONData之前显示HUD,然后在收到数据时隐藏它:

dispatch_async(dispatch_get_main_queue(), ^{
   l.uiImage = image;
   [MBProgressHUD hideHUDForView:self.view animated:YES];
});

虽然我个人会在loadJSONData中进行回调并在完成程序段中执行HUD解雇。