2011-03-09 107 views
2

我收到以下代碼。在撥打webservice時顯示警告

UIActivityIndicator *activity = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: 
                UIActivityIndicatorStyleWhite]; 


UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Processing" delegate:self otherButtonTitles:nil]; 
    [alert addSubview:activity];  
    [activity startAnimating];  
    [alert show]; 

WebServiceController *web = [[WebServiceController alloc]init]; 

NSDictionary *dict = [web getDetails]; 

問題是警報沒有顯示。 WebServiceController是一個XML解析器,它從指定的URL獲取詳細信息並返回它們。警報應在服務被調用時顯示,因爲獲取詳細信息需要時間。但它只在服務呼叫結束後才顯示警報。這是爲什麼?

回答

3

因爲[alert show]將需要動畫,因爲服務控制器調用發生在主線程上,主線程忙於執行服務調用,阻止了alert視圖動畫的執行。

您需要在後端線程上執行ServiceCall,請參閱NSOperation或PerformSelectorOnBackgroundThread,確保您將具有AlertView的ViewController委託傳遞給後端線程,並在服務調用完成後立即回調委託。確保使用performSelectorOnMainThread在主線程上執行對回調的調用。所有與UI相關的調用都應該在主線程上執行。

+0

你可以給一些使用performSelectorOnBackgroundThread方法的例子的鏈接? –

1

添加到上面的帖子,你必須寫這樣的警告:

UIActivityIndicator *activity = [[UIActivityIndicator alloc] initWithActivityIndicatorStyle: 
                UIActivityIndicatorStyleWhite]; 


UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Processing" delegate:self otherButtonTitles:nil]; 
    [alert addSubview:activity];  
    [activity startAnimating];  
    [alert show]; 

[self performSelectorInBackground:@selector(doTheWork) object:nil]; 

你需要聲明一個函數(doTheWork)的如下會照顧Web服務調用:

-(void)doTheWork { 

WebServiceController *web = [[WebServiceController alloc]init]; 

NSDictionary *dict = [web getDetails]; 

[alert dismissWithClickedButtonIndex:0 animated:YES]; //dismissing the alert 

}