1. 程式人生 > >多執行緒GCD,UIActivityIndicatorView的等待畫面

多執行緒GCD,UIActivityIndicatorView的等待畫面

    //在Login Lable上新增spinner
    UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    [spinner startAnimating];
    spinner.center = self.loginButton.center;
    [self.view addSubview:spinner]; 
   //多執行緒等待login的返回值    
    dispatch_queue_t downloadQueue = dispatch_queue_create("data downloader",NULL);
    dispatch_async(downloadQueue,^{
        NSString *returnedValue = [self loginConnection];
        dispatch_async(dispatch_get_main_queue(),^{
         if(returnedValue == @"ok"){
                [self performSegueWithIdentifier:@"ShowHomePage" sender:self];
            }else(returnedValue == @"Authentification Failed"){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Authentification Failed." message:@"Authentification Failed." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                spinner.hidden = YES;
                [self.loginButton setTitle:@"Login" forState:UIControlStateNormal];
            }
        });
    });

注1:[self loginConnection] 不應涉及介面元素的操作,例如不能把 UIAlertView 程式碼放入loginConnection中。
注2:[self loginConnection] 中的方法必須是同步的,比如sendSynchronousRequest