2011-07-04 42 views
6

我需要從三個不同的URL下載三組不同的數據。我決定使用ASIHTTPRequest。其中兩個URL是我需要解析的JSON提要,其中一個是我需要在本地存儲的.txt文件在線。ASIHTTPRequest上的多個請求

現在是在ASIHTTPRequest的網站異步請求的例子顯示如下:

- (IBAction)grabURLInBackground:(id)sender { 
    NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [request setDelegate:self]; 
    [request startAsynchronous]; 
} 

要通過多個URL,我可以在三個不同的網址,稱「要求」。但我不知道如何在requestFinished方法中處理它們。該文檔顯示爲:

- (void)requestFinished:(ASIHTTPRequest *)request { 
    // Use when fetching text data 
    NSString *responseString = [request responseString]; 

    // Use when fetching binary data 
    NSData *responseData = [request responseData]; 
} 

該方法如何區分不同的請求,以便我可以以不同的方式處理?

謝謝

回答

12

您可以通過

  • 設置請求
  • 的didFinishSelector(和didFailSelector等)設置不同的方法的用戶信息字典
  • 使用不同請求之間的區別代表不同的班級
  • 使用模塊
  • 使用請求的標籤屬性
  • 子ASIHTTPRequest和覆蓋覆蓋requestFinished:和failWithError:(只推薦用於複雜的情況下)
+2

您也可以在最新版本中使用request.tag。 – JosephH

+0

我強烈建議使用塊。您的代碼將更乾淨,並且易於遵循。 –

+0

塊如何工作? – darksky

1

可以設置REQ的用戶名和標記。

這是imageview的示例。 REQ。

UIImageView *imgV=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 416)]; 

    ASIHTTPRequest *req=[ASIHTTPRequest requestWithURL:[NSURL URLWithString:[self.arr objectAtIndex:i]]]; 
    [req setUsername:[NSString stringWithFormat:@"%i",i]]; 
    [req setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:imgV,@"imgV",nil]]; 
    [req setDelegate:self]; 
    [req startAsynchronous]; 
    [imgV setContentMode:UIViewContentModeScaleToFill]; 
    [imgV setClipsToBounds:YES]; 
    [imgV setTag:kTagImageViewInScrollView]; 
    [scr2 addSubview:imgV]; 
    [scr2 setDelegate:self]; 
    [imgV release]; imgV=nil; 

和requestFinished

- (void)requestFinished:(ASIHTTPRequest *)request { 
    [(UIImageView*)[[request userInfo] valueForKey:@"imgV"] setImage:[UIImage imageWithData:[request responseData]]]; 

} 
+0

這個答案包含正確的響應,但應該修剪一下。 –

1

,如果你有不同的URL可以檢查ASIHTTPRequest的originalURL財產。

或者您可以使用[請求散列]來獲取每個對象的NSObject散列,並在稍後檢查。

3

你只需要兩段代碼。一個 '標籤' 您的網址:

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url]; 
[request setUserInfo:[NSDictionary dictionaryWithObjectsAndKeys:@"identifierX", @"typeOfRequest",nil]]; 

,另一種識別它:

if ([[[request userInfo] valueForKey:@"typeOfRequest"] isEqualToString:@"identifierX"]){ 
     // Do here whatever you need to do for the url associated with identifierX 
    } 

這應該是它!