svprogresshud没有显示在主线程上

时间:2015-07-07 14:01:03

标签: ios objective-c afnetworking-2

在我的tableviewcontroller的viewdidload上,我有以下

[SVProgressHUD showWithStatus:@"Loading"];
[self getData];
[SVProgressHUD dismiss];

在getData方法上,我使用AFNetworking从后端api获取数据。由于这是一个异步调用,我希望我的SVProgressHUD显示。

  -(void) getData {
     AFHTTPRequestOperationManager * reqManager =AFHTTPRequestOperationManager manager];
     AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    //set auth token..etc 
   [reqManager GET:urlString parameters:nil 
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
             //code for success....
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       //code for failure
    }];
}

但它根本没有显示出来。显然我正在研究我的主线程。我哪里错了?

2 个答案:

答案 0 :(得分:1)

问题不在于它没有显示在主线程上,而是它显示和被解雇的速度太快以至于你没有看到它。这是因为GET是一种异步方法。

解决方案是采用完成处理程序模式,即getData在异步方法完成时将调用的代码块:

- (void)getDataWithCompletionHandler:(void (^)(NSError *))completionHandler {
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //set auth token..etc
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //code for success....

        if (completionHandler) {
            completionHandler(nil);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //code for failure

        if (completionHandler) {
            completionHandler(error);
        }
    }];
}

[SVProgressHUD showWithStatus:@"Loading"];
[self getDataWithCompletionHandler:^(NSError *error) {
   [SVProgressHUD dismiss];
}];

此模式允许您将dismiss的调用推迟到异步过程完成,但它也将SVProgressHUD代码保存在一个区域中(而不是将其分散并隐藏与UI相关的内容)网络方法中的代码。)

答案 1 :(得分:0)

问题是你在方法调用之后立即显示hud,如

[self getData];
[SVProgressHUD dismiss];

这就是问题所在。将解雇代码移至

-(void) getData {
     AFHTTPRequestOperationManager * reqManager =AFHTTPRequestOperationManager manager];
     AFHTTPRequestSerializer *serializer = [AFHTTPRequestSerializer serializer];
    //set auth token..etc 
   [reqManager GET:urlString parameters:nil 
    success:^(AFHTTPRequestOperation *operation, id responseObject) {
             //code for success....
             [SVProgressHUD dismiss];
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error) {
       //code for failure
              [SVProgressHUD dismiss];
    }];
}

您可以看到dismiss调用成功和失败的webservice调用,并通过

调用getData方法
[SVProgressHUD showWithStatus:@"Loading"];
[self getData];

从此处删除[SVProgressHUD dismiss]