2011年8月4日 星期四

sendSynchronousRequest 狀態下如何顯示忙碌訊息

NSURLConnection 類別中的 sendSynchronousRequest 方法,
是一個同步處理的機制,也就是說當此方法ㄧ被呼叫,該執行緒就會被整個咬住了,
通常來說我們會希望能加入一些畫面提醒的機制(例如轉圈圈),有兩種解決來提供:

解法一(程式碼可以改最少):
- (void)loadInOnePart {

//...other real code

UIAlertView *avBusy = [[[UIAlertView alloc] initWithTitle:@"Busy busy" message:nil delegate:nil
cancelButtonTitle:nil otherButtonTitles:nil] autorelease];
[avBusy show];

UIActivityIndicatorView *aiBusy = [[[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite] autorelease];
[aiBusy startAnimating];
[avBusy addSubview:aiBusy];

aiBusy.center = CGPointMake(avBusy.bounds.size.width / 2, avBusy.bounds.size.height / 2 + 10);

[[NSRunLoop currentRunLoop] runUntilDate:[NSDate date]];

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

[avBusy dismissWithClickedButtonIndex:0 animated:YES];
}

解法二(程式碼分割要考慮整體架構):
- (void)loadPart1 {
activityIndicator = [[[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]
autorelease];
[self.view addSubview:activityIndicator];
[activityIndicator startAnimating];
[self performSelector:@selector(loadPart2) withObject:nil afterDelay:0];
}

- (void)loadPart2 {
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[activityIndicator stopAnimating];
}


參考資料來源

沒有留言: