開源類庫之一 (ASIHTTPRequest)

ASIHTTPRequest雖然很久沒有更新了,但是他仍然是一個非常流行的iOS平臺網絡通信類庫,使用ASIHTTPRequest之後,大大簡化了iOS平臺的網絡編程。其以方便的接口對同步、異步的網絡傳輸進行了傳輸,將ASIHTTPRequest添加到自己的項目也非常方便,將類庫中所有文件拷貝到一個文件夾中,然後將此文件夾添加到項目中,同時要添加如下圖CFNetWork之下所示的類庫,就可以使用ASIHTTPRequest了:



使用ASIHTTPRequest步驟非常簡答,在一般應用開發中,網絡連接基本上使用的都是異步方式,下面簡單演示一下最簡單的異步通訊方法


  1. #import "ASIHTTPRequest.h"  
  2.   
  3. - (void) requestDataFromServer  
  4. {  
  5.     NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
  6.     NSURL* url = [NSURL URLWithString: @"www.fakeurl.com"];  
  7.     ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL: url];  
  8.     [request setTag: 1024];  
  9.     [request setTimeOutSeconds: 3];  
  10.     [request setAllowCompressedResponse:YES];  
  11.     [request setDelegate:self];  
  12.     [request startAsynchronous];  
  13.     [pool drain];  
  14. }  
  15.   
  16. - (void)requestFinished:(ASIHTTPRequest *)request  
  17. {  
  18.     NSString* rawString = [request responseString];  
  19.     if (request.tag == 1024) {  
  20.         //處理網絡返回結果  
  21.      }   
  22. }  
  23.   
  24. - (void)requestFailed:(ASIHTTPRequest *)request  
  25. {  
  26.     if (request.tag == 1024) {  
  27.         //處理網絡錯誤  
  28.      }   
  29. }   

注意上面的兩個函數中,後面連個爲ASIHTTPRequest的delegate函數,其聲明類型不能改變,只要在生成ASIHTTPRequest時的deleage設成了self,那麼最後返回結果,不管是成功調用還是網絡失敗,都會調用這兩個函數中的對應的一個。
發佈了36 篇原創文章 · 獲贊 0 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章