从AFHTTPRequestOperation更新主线程上的UI

时间:2013-03-01 16:02:07

标签: ios multithreading grand-central-dispatch afnetworking

我为iOS应用程序构建了一个Rails后端,允许用户在授权设备后才能访问RESTful API。基本上,通过检索令牌来管理授权。

当用户提交用户名和密码时,将使用AFHTTPRequestOperation调用Web服务(请参阅下面的代码)。我还向用户显示HUD(MBProgressHUD)以跟踪请求的进度。我已经设置了成功和失败的回调,我想更新HUD并让它在屏幕上显示更新的消息几秒钟然后解除它。

//Set HUD
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.mode = MBProgressHUDModeIndeterminate;
hud.labelText = @"Authenticating";

//Set HTTP Client and request
NSURL *url = [NSURL URLWithString:@"http://localhost:3000"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient setParameterEncoding:AFFormURLParameterEncoding]; //setting x-www-form-urlencoded
NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"/api/v1/tokens.json" parameters:@{@"password":_passwordField.text, @"email":_emailField.text}];

//Set operation
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

//Success and failure blocks
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
    NSError *error;
    NSDictionary* jsonFromData = (NSDictionary*)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
    NSLog(@"%@", jsonFromData);
    _statusLabel.text = @"Device authenticated!";
    hud.customView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"37x-Checkmark.png"]];
    hud.mode = MBProgressHUDModeCustomView;
    hud.labelText = @"Authenticated!";
    sleep(2);
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error){
    NSLog(@"Error");
    sleep(2);
    _statusLabel.text = @"Wrong username or password!";
    [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
}];

调用成功/失败操作回调时:

  • 我尝试更新HUD模式和文字;
  • 我等了sleep()几秒钟;
  • 我解雇了HUD [MBProgressHUD hideAllHUDsForView:self.view animated:YES];;

我也尝试使用dispatch_queue_t dispatch_get_main_queue(void);并在主线程上运行HUD更新,但无济于事。

关于我出错的任何想法?

0 个答案:

没有答案