ASIHTTPRequest雖然很久沒有更新了,但是他仍然是一個非常流行的iOS平臺網絡通信類庫,使用ASIHTTPRequest之後,大大簡化了iOS平臺的網絡編程。其以方便的接口對同步、異步的網絡傳輸進行了傳輸,將ASIHTTPRequest添加到自己的項目也非常方便,將類庫中所有文件拷貝到一個文件夾中,然後將此文件夾添加到項目中,同時要添加如下圖CFNetWork之下所示的類庫,就可以使用ASIHTTPRequest了:
使用ASIHTTPRequest步驟非常簡答,在一般應用開發中,網絡連接基本上使用的都是異步方式,下面簡單演示一下最簡單的異步通訊方法
- #import "ASIHTTPRequest.h"
- - (void) requestDataFromServer
- {
- NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
- NSURL* url = [NSURL URLWithString: @"www.fakeurl.com"];
- ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL: url];
- [request setTag: 1024];
- [request setTimeOutSeconds: 3];
- [request setAllowCompressedResponse:YES];
- [request setDelegate:self];
- [request startAsynchronous];
- [pool drain];
- }
- - (void)requestFinished:(ASIHTTPRequest *)request
- {
- NSString* rawString = [request responseString];
- if (request.tag == 1024) {
- //處理網絡返回結果
- }
- }
- - (void)requestFailed:(ASIHTTPRequest *)request
- {
- if (request.tag == 1024) {
- //處理網絡錯誤
- }
- }
注意上面的兩個函數中,後面連個爲ASIHTTPRequest的delegate函數,其聲明類型不能改變,只要在生成ASIHTTPRequest時的deleage設成了self,那麼最後返回結果,不管是成功調用還是網絡失敗,都會調用這兩個函數中的對應的一個。