Showing alert while calling webservice

╄→гoц情女王★ 提交于 2020-02-04 11:49:01

问题


i have the following code.

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];

The problem is that the alert is not getting displayed. The WebServiceController is an XML parser which gets details from a specified URL and returns them. The alert should be shown while the service is called as it takes time to get the details. But it displays the alert only after the service call is over. Why is that?


回答1:


because [alert show] will require animation, since the service controller call is taking place on the main thread, the main thread is busy executing the service call, blocking the alert view animation to execute.

You need to perform the ServiceCall on backend thread, see NSOperation or PerformSelectorOnBackgroundThread, make sure you pass in delegate of the ViewController that has the AlertView to the backend thread, callback the delegate as soon as the service call is completed. Make sure you perform the call for the callback on the mainthread using performSelectorOnMainThread. All UI related calls should be executed on the main thread.




回答2:


Adding to the above post, you have to write the alert like this:

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];

You need to declare a function (doTheWork) which will take care of the web service call as follows:

-(void)doTheWork {

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

NSDictionary *dict = [web getDetails];

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

}


来源:https://stackoverflow.com/questions/5242818/showing-alert-while-calling-webservice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!