ASIHTTPRequest 運用

原文轉自:http://tech.hexun.com/2011-02-02/127151655.html

添加一個同步request這是使用ASIHTTPRequest最簡單的方法。發送一個startSynchronous消息。將在同一個進程中執行請求,在完成之後釋放控制。

  通過error屬性來察看問題。

  使用responseString可以得到string類型的response信息。

  responseData方法用來獲取一個NSData對象,或者更大的文件。不要使用這個方法來獲取二進制的數據。

  DownloadDestinationPath方法用來設置request,來下載到一個文件中。

    創建一個同步request

  - (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];

  }

  }

  注意:一般來說,使用異步請求優先於同步請求。當你從main進程中使用同步的ASIHTTPRequest。你的應用程序界面將會被鎖住,並且,在這期間不能使用。

  同步request只是用於沒有界面的應用程序,例如終端。或者你運行在一個單獨的進程中,並且你對它進行維護。

  Creatingan asynchronous request

  創建一個異步request

  示例代碼看起來幹着同樣的事情(或者理解爲代碼開起來是一樣的),但是,request是在後臺運行的

  - (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];

  }

  注意,我們爲request設置委託,這樣,我們就可以接收消息,無論request完成了還是失敗了。

  這是一個最簡單的創建一個異步的request的方法,並且,它會運行在當前進程裏。對於更復雜的情況,你可能想創建一個隊列,我們可以覆蓋下一個(youmight want to create your own queue, which is what we"ll covernext.這裏翻譯的非常勉強….英語差啊…);

  Using aqueue

  使用一個隊列

  這個示例依然是做同樣的事情,但是,我們將爲我們的request添加一個NSOperationQueue對象。

  使用NSOperationQueue(或ASINetWorkQueue,見下面示例)將給你對異步request更多的控制。當使用隊列的時候,只有確定數量的request可以同時運行。如果你添加的request超過了隊列的 maxConcurrentOperationCount屬性,request將在其他request運行完了之後運行。

  - (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];

  }

  在上面的示例中,"queue"是我們的控制器保留NSOperationQueue的產物。

  我們設置selectors,selectors將在request成功或者失敗之後被執行。如果你不設置這些,將會調用默認的(requestFinished和requestFailed).

發佈了45 篇原創文章 · 獲贊 6 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章