AFnetworking waitUntilFinish无法正常工作 [英] AFnetworking waitUntilFinish not working

查看:90
本文介绍了AFnetworking waitUntilFinish无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个使用AFNetworking库的项目。我用它来检查Web服务的登录名和密码。如果可以的话,这会给我200码。如果是200,则将布尔值设置为true,以便应用程序可以继续。但是此布尔值未在正确的时间设置。我总是需要在登录按钮上按两次。这是设置布尔值的代码。

I am making a project that uses the AFNetworking Library. I use it to check for a login and password with the webservice. This gives me a 200-code back if it is ok. If it is 200, I set a boolean to true so that the application can continue. But this boolean is not set at the right time. I always need to press two times on my login button before it works. Here is my code to set the boolean.

    - (BOOL)credentialsValidated {
    self.progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.progressHUD.labelText = @"Loading";
    self.progressHUD.mode = MBProgressHUDModeIndeterminate;
    self.progressHUD.dimBackground = YES;
     [[API sharedInstance] loginCommand:[NSMutableDictionary dictionaryWithObjectsAndKeys:_txtLogin.text,@"email",_txtPass.text,@"pwd", nil] onCompletion:^(NSDictionary *json){
     //completion
         if(![json objectForKey:@"error"]){
             NSLog(@"status %@",[json valueForKeyPath:@"data.status"]);
             if([[json valueForKeyPath:@"data.status"]intValue] == 200){
                //Create user object


                _loginstatus =  YES;
                [self.progressHUD hide:YES afterDelay:5];
             }else{
                 //show validation
                 _txtLogin.text = @"";
                 _txtPass.text = @"";
                 _loginstatus = NO;
             }
         }else {
             NSLog(@"Cannot connect to the server");
         }
     }];
     if(_loginstatus){
         NSLog(@"true");
    }else{
        NSLog(@"false");
    }
    [self.progressHUD hide:YES afterDelay:5];
     return _loginstatus;
}

这是我的API代码。

-(void)loginCommand:(NSMutableDictionary *)params onCompletion:(JSONResponseBlock)completionBlock{
    NSLog(@"%@%@",kAPIHost,kAPILogin);
    NSMutableURLRequest *apiRequest = [self multipartFormRequestWithMethod:@"POST" path:kAPILogin parameters:params constructingBodyWithBlock:^(id <AFMultipartFormData>formData){
        //TODO: attach file if needed

    }];
    AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:apiRequest];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //success !
        NSLog(@"SUCCESSSS!");
        completionBlock(responseObject);
    }failure:^(AFHTTPRequestOperation *operation, NSError *error){
        //Failure
        NSLog(@"FAILUREE!");
        completionBlock([NSDictionary dictionaryWithObject:[error localizedDescription] forKey:@"error"]);
    }];
    [operation start];

}

当我放在以下时[开始] [operation waitUntilFinish] 代码,应用崩溃。

When I put below [operation start] the [operation waitUntilFinish] code, the app crashes.

有人可以帮我吗?

亲切的问候

日志
这是我两次登录后我的日志的打印

LOG Here is a print of my log after I 2 two times pressed the login button

2012-12-28 09:36:00.547 Offitel[6532:907] http://virtuele-receptie.******.sanmax.be/nl/webservice/company-user/****/*****/**************
2012-12-28 09:36:00.561 Offitel[6532:907] false
2012-12-28 09:36:01.604 Offitel[6532:907] SUCCESSSS!
2012-12-28 09:36:01.605 Offitel[6532:907] status 200
2012-12-28 09:36:20.742 Offitel[6532:907] aanmelden pressed
2012-12-28 09:36:20.746 Offitel[6532:907] http://virtuele-receptie.******.sanmax.be/nl/webservice/company-user/****/*****/**************
2012-12-28 09:36:20.748 Offitel[6532:907] true
2012-12-28 09:36:22.184 Offitel[6532:907] SUCCESSSS!
2012-12-28 09:36:22.184 Offitel[6532:907] status 200


推荐答案

如果执行此操作

return _loginstatus;

您没有等待操作完成,因此您没有返回服务器要发送到的内容你的申请。在这种情况下,我通常要做的是在触发登录操作时显示 UIActivityIndi​​cator ,并且在服务器响应之前不执行任何操作。然后,我为所有变量设置适当的值,在这种情况下,我会选择进入主屏幕。

You are not waiting the operation to finish, so you're not returning what your server is sending to your application. What I usually do in this cases is display an UIActivityIndicator when the login action is fired, and do nothing till' the server has responded. Then, I set the proper values to any variables and in this case I would segue to home screen.

请记住,当您使用 AFNetworking时您始终在做异步操作。

Remember that when you're using AFNetworking you are always doing async stuff.

编辑

代码示例:

- (void)loginActionWithPassword:(NSString *)pass
{
    // Add progress HUD to show feedback
    // I'm using MBProgressHUD library: https://github.com/jdg/MBProgressHUD#readme
    self.progressHUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.progressHUD.labelText = @"Loading";
    self.progressHUD.mode = MBProgressHUDModeIndeterminate;
    self.progressHUD.dimBackground = YES;

    // Launch the action to the server
    [Actions loginWithEmail:[self.textEmail.text lowercaseString] andPassword:pass success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        if ([Actions requestFailed:JSON]) {
            LOG(@"ERROR %@ / %@ / %@ \n", pass, request, response, JSON);
            if ([JSON[@"MSG"] isEqualToString:@"USER_NOT_REGISTERED"]) {
                self.progressHUD.labelText = @"User doesn't exist";
                self.textEmail.text = @"";
                self.textPassword.text = @"";
            } else if ([JSON[@"MSG"] isEqualToString:@"PASSWORD_INCORRECT"]) {
                self.progressHUD.labelText = @"Wrong password";
                self.textPassword.text = @"";
            }
            [self.progressHUD hide:YES afterDelay:[Utils hudDuration]];
            return;
        }
        // If everything went OK, go to this function to save user data
        // and perform segue to home screen (or dismiss modal login view)
        [self onLoginSuccessWithPassword:pass JSON:JSON response:response];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
        // If something fails, display an error message
        LOG(@"ERROR:(%@): %@ / %@ / %@ / %@ \n", pass, request, response, error, JSON);
        self.progressHUD.labelText = @"Something went wrong, try again";
        [self.progressHUD hide:YES afterDelay:[Utils hudDuration]];
        return;
    }];
}

这篇关于AFnetworking waitUntilFinish无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆