使用MBProgressHUD和NSSession加载数据同步

时间:2014-02-20 08:48:32

标签: objective-c ios7 objective-c-blocks

我有一种异步加载数据的方法。

-(void)loadingDataAsynchronously{

    NSURL *url = [NSURL URLWithString:@"http://vbahrain.azurewebsites.net/api/yearapi"];

    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];


    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDownloadTask  *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {

        NSData *data = [[NSData alloc] initWithContentsOfURL:location];


        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];

        self.yearBucket = [NSMutableArray array];

        for (NSDictionary * dict in array) {

            Year *year = [[Year alloc ]init];

            year.yearName =[dict objectForKey:@"Year"];
            year.speeches = [dict objectForKey:@"Speeches"];

            [self.yearBucket addObject:year];


        }

        dispatch_async(dispatch_get_main_queue(), ^{


            [self.tableView reloadData];

        });



    }];
    [task resume];
}

这是我用来加载MPProgressHUD的代码。

 - (void)viewDidLoad
{
    [super viewDidLoad];

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];

    HUD.mode = MBProgressHUDModeDeterminate;
    HUD.labelText = @"Loading";
    HUD.delegate = self;


    [HUD showWhileExecuting:@selector(loadingDataAsynchronously) onTarget:self withObject:Nil animated:YES];


}

MPProgressHUD出现并在一秒钟内消失。如何显示MPProgressHUD以显示在后台线程中加载数据的实际进度。

1 个答案:

答案 0 :(得分:0)

您可以尝试在loadingDataAsynchronously方法中删除HUD。

 - (void)viewDidLoad
{
    [super viewDidLoad];

   [MBProgressHUD showHUDAddedTo:self.view animated:YES];
   dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), ^{
       [self loadingDataAsynchronously];
   });


}

-(void)loadingDataAsynchronously{

    NSURL *url = [NSURL URLWithString:@"http://vbahrain.azurewebsites.net/api/yearapi"];

    ...

    dispatch_async(dispatch_get_main_queue(), ^{

        [self.tableView reloadData];

        [MBProgressHUD hideHUDForView:self.view animated:YES];

    });

    ...

}