2013-02-26 110 views
2

我正在構建一個登錄模塊,用戶輸入的憑據在後端系統中進行驗證。我正在使用異步調用來驗證憑據,並且在用戶通過身份驗證後,我使用方法presentViewController:animated:completion繼續下一個屏幕。問題是presentViewController方法啓動需要花費一些時間,直到出現下一個屏幕。恐怕我之前撥打sendAsynchronousRequest:request queue:queue completionHandler:的電話會以某種方式造成副作用。UIViewController presentViewController:動畫:完成 - 需要4到6秒才能啓動

只是爲了確保當我說4 - 6秒是命令presentViewController:animated:completion開始後。我說這是因爲我正在調試代碼並監視調用方法的時刻。

第一:NSURLConnection方法被稱爲:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0]; 

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) 

二:UIViewController方法被調用採取異常運行時間

UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"]; 

[self presentViewController:firstViewController animated:YES completion:nil]; 

任何幫助表示讚賞。

謝謝, 馬科斯。

+0

那麼你是否從完成塊中調用表示代碼? – 2013-02-26 00:34:27

+0

是的,我正在從完成塊打電話給它 – vilelam 2013-02-26 00:35:52

回答

10

這是從後臺線程操縱UI的典型症狀。您需要確保只在主線程上調用UIKit方法。完成處理,不能保證在任何特定的線程中調用,所以你必須做這樣的事情:

[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     UIViewController *firstViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"FirstView"]; 
     [self presentViewController:firstViewController animated:YES completion:nil]; 
    }); 
} 

這可以保證你的代碼在主線程上運行。

+0

謝謝卡爾!你是男人!它爲我節省了很多時間。 – vilelam 2013-02-26 00:56:04

+0

@vilelam謝謝,很高興它幫助! – 2013-02-26 01:10:35

相關問題