1. 同步意為著線程阻塞,在主線程中使用此方法會不響應任何使用者事件。所以,在應用程式設計時,大多被用在專門的子線程增加使用者體驗,或用非同步請求代替。
- - (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 的一個執行個體
startSynchronous 方法啟動同步訪問
由於是同步請求,沒有基於事件的回調方法,所以從 request的error 屬性擷取錯誤資訊
responseString,為請求的返回 NSString 資訊 *
注意:在這裡我發現NsUrlRequset和connect系統Api就可以配合做到效果。也不需要到移植開原始碼
2. 非同步請求的好處是不阻塞當前線程,但相對於同步請求略為複雜,至少要添加兩個回調方法來擷取非同步事件
- - (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 來啟動網路請求
在這裡實現了兩個 delegate 的方法,當資料請求成功時會調用 requestFinished,請求失敗時(如網路問題或伺服器內部錯誤)會調用 requestFailed。
PS: 非同步請求一般來說更常用一些,而且裡面封裝都挺不錯的,至少比symbian等平台方便的多,而且還可以修改原始碼。多數這個跟隊列混合封裝來達到圖片和非同步下載包的目的(已實現)。
3. 請求隊列提供了一個對非同步請求更加精準豐富的控制。如:可以設定在隊列中同步請求的串連數。往隊列裡添加的請求執行個體數大於 maxConcurrentOperationCount 時,請求執行個體將被置為等待,直到前面至少有一個請求完成並出列才被放到隊列裡執行。這也適用於當我們有多個請求需求按順序執行的時候(可能是業務上的需要,也可能是軟體上的調優),僅僅需要把 maxConcurrentOperationCount 設為“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];
- }
建立 NSOperationQueue,這個 Cocoa 架構的執行任務(NSOperation)的任務隊列。我們通過 ASIHTTPRequest.h 的源碼可以看到,此類本身就是一個 NSOperation 的子類。也就是說它可以直接被放到”任務隊列”中並被執行