简体   繁体   English

UI无法立即显示微调器

[英]UI not displaying spinner instantly

Hey, I'm creating an iOS app that requires the user to login using a username and password, this username and password is then sent to a web server to be authenticated. 嘿,我正在创建一个iOS应用程序,要求用户使用用户名和密码登录,然后将此用户名和密码发送到Web服务器进行身份验证。 While it sends the request and waits for the response I show a UIActivityIndicator. 当它发送请求并等待响应时,我显示了一个UIActivityIndi​​cator。

The problem I get is that sometimes the UIActivityIndicator appears straight away on the button press and other times it appears only after a few seconds have passed. 我得到的问题是,有时UIActivityIndi​​cator会在按下按钮后立即显示,而其他时候仅在几秒钟后才出现。 Am guessing its because the OS is executing another thread before updating the UI but I would like to know if anyone knows for sure what could be causing this sometime delay or is it just that my code is at fault. 我猜是因为操作系统在更新UI之前正在执行另一个线程,但是我想知道是否有人能确定是什么原因导致此时间延迟,或者仅仅是我的代码有问题。

My code below: 我的代码如下:

-(void)loginPressed:(id)sender{

    if ([self validateForm]) {

        [self startLoadingAnimation:@"CONNECTING"];

        [Session theSession].authenicatedUsername = usernameTextField.text;
        [Session theSession].authenicatedPassword = passwordTextField.text;

        usernameTextField.text = @"";
        passwordTextField.text = @"";

        [self setUserDetailsBasedOnUserID:[Session theSession].authenicatedUsername password:[Session theSession].authenicatedPassword]; 

    }else {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"MISSING_LOGIN_DETAILS_TITLE", @"")
                                                        message:NSLocalizedString(@"MISSING_LOGIN_MESSAGE", @"")
                                                       delegate:self
                                              cancelButtonTitle:NSLocalizedString(@"OK_BUTTON", @"")
                                              otherButtonTitles:nil];

        [alert show];
        [alert release];
    }
}

Thanks 谢谢

You should do networking asynchronously, otherwise, you'll block the main (UI) thread while potentially waiting a long time for the server to respond (you don't know what kind of connection your users have etc.). 您应该异步进行联网,否则,您将阻塞主(UI)线程,同时可能等待很长时间以使服务器响应(您不知道用户具有哪种连接等)。

If you absolutely can't do this either in a background thread or using NSURLConnection's asynchronous interface, you can first let your runloop return to update the UI (start the activity indicator) and then start the task, like this: 如果您绝对不能在后台线程中或使用NSURLConnection的异步接口来执行此操作,则可以首先让runloop返回以更新UI(启动活动指示器),然后启动任务,如下所示:

- (void)loginPressed:(id)sender {
  [activityIndicator startAnimating];
  [self performSelector:@selector(doLogin) withObject:nil afterDelay:0.0];
}

- (void)doLogin {
  //perform your task here...
}

But as I said, this is generally bad practice... 但是正如我所说,这通常是不好的做法...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM