我为 iOS 应用程序构建了一个 Rails 后端,它允许用户仅在授权设备后才能访问 RESTful API。基本上授权是通过检索令牌来管理的。
当用户提交用户名和密码时,网络服务会被调用AFHTTPRequestOperation
(见下面的代码)。我还向用户显示 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 更新,但无济于事。
关于我做错了什么的任何想法?