iOS網(wǎng)絡(luò)編程之同步、異步、請求隊(duì)列
1. 同步意為著線程阻塞,在主線程中使用此方法會不響應(yīng)任何用戶事件。所以,在應(yīng)用程序設(shè)計(jì)時,大多被用在專門的子線程增加用戶體驗(yàn),或用異步請求代替。
- - (IBAction)grabURL:(id)sender
- {
- NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request startSynchronous];
- NSError *error = [request error];
- if (!error) {
- NSString *response = [request responseString];
- }
- }
用 requestWithURL 快捷方法獲取 ASIHTTPRequest 的一個實(shí)例
startSynchronous 方法啟動同步訪問
由于是同步請求,沒有基于事件的回調(diào)方法,所以從 request的error 屬性獲取錯誤信息
responseString,為請求的返回 NSString 信息 *
注意:在這里我發(fā)現(xiàn)NsUrlRequset和connect系統(tǒng)Api就可以配合做到效果。也不需要到移植開源代碼
2. 異步請求的好處是不阻塞當(dāng)前線程,但相對于同步請求略為復(fù)雜,至少要添加兩個回調(diào)方法來獲取異步事件
- - (IBAction)grabURLInBackground:(id)sender
- {
- NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDelegate:self];
- [request startAsynchronous];
- }
- - (void)requestFinished:(ASIHTTPRequest *)request
- {
- // Use when fetching text data
- NSString *responseString = [request responseString];
- // Use when fetching binary data
- NSData *responseData = [request responseData];
- }
- - (void)requestFailed:(ASIHTTPRequest *)request
- {
- NSError *error = [request error];
- }
與上面不同的地方是指定了一個 “delegate”,并用 startAsynchronous 來啟動網(wǎng)絡(luò)請求
在這里實(shí)現(xiàn)了兩個 delegate 的方法,當(dāng)數(shù)據(jù)請求成功時會調(diào)用 requestFinished,請求失敗時(如網(wǎng)絡(luò)問題或服務(wù)器內(nèi)部錯誤)會調(diào)用 requestFailed。
PS: 異步請求一般來說更常用一些,而且里面封裝都挺不錯的,至少比symbian等平臺方便的多,而且還可以修改源代碼。多數(shù)這個跟隊(duì)列混合封裝來達(dá)到圖片和異步下載包的目的(已實(shí)現(xiàn))。
3. 請求隊(duì)列提供了一個對異步請求更加精準(zhǔn)豐富的控制。如:可以設(shè)置在隊(duì)列中同步請求的連接數(shù)。往隊(duì)列里添加的請求實(shí)例數(shù)大于 maxConcurrentOperationCount 時,請求實(shí)例將被置為等待,直到前面至少有一個請求完成并出列才被放到隊(duì)列里執(zhí)行。這也適用于當(dāng)我們有多個請求需求按順序執(zhí)行的時候(可能是業(yè)務(wù)上的需要,也可能是軟件上的調(diào)優(yōu)),僅僅需要把 maxConcurrentOperationCount 設(shè)為“1”。
- - (IBAction)grabURLInTheBackground:(id)sender
- {
- if (![self queue]) {
- [self setQueue:[[[NSOperationQueue alloc] init] autorelease]];
- }
- NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
- ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
- [request setDelegate:self];
- [request setDidFinishSelector:@selector(requestDone:)];
- [request setDidFailSelector:@selector(requestWentWrong:)];
- [[self queue] addOperation:request]; //queue is an NSOperationQueue
- }
- - (void)requestDone:(ASIHTTPRequest *)request
- {
- NSString *response = [request responseString];
- }
- - (void)requestWentWrong:(ASIHTTPRequest *)request
- {
- NSError *error = [request error];
- }
創(chuàng)建 NSOperationQueue,這個 Cocoa 架構(gòu)的執(zhí)行任務(wù)(NSOperation)的任務(wù)隊(duì)列。我們通過 ASIHTTPRequest.h 的源碼可以看到,此類本身就是一個 NSOperation 的子類。也就是說它可以直接被放到”任務(wù)隊(duì)列”中并被執(zhí)行
【編輯推薦】