2012-02-21 28 views
0

我有一個使用AsiHTTPRequest的類。我想打一個方法是這樣的:使用AsiHTTPRequest的方法返回值

-(NSData*)downloadImageFrom: (NSString*)urlString; 
{ 
    // Set reponse data to nil for this request in the dictionary 
    NSMutableData *responseData = [[NSMutableData alloc] init]; 
    [responseDataForUrl setValue:responseData forKey:urlString]; 

    // Make the request 
    NSURL *url = [NSURL URLWithString:urlString]; 
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
    [responseDataForUrl setValue:responseData forKey:[request url]]; 
    [request setDelegate:self]; 
    [request startAsynchronous]; 

    // Wait until request is finished (???? Polling ?????) 
    // while(responsedata = nil) { 
    // do nothing 
    // } BAD SOLUTION 

    return responseData; 

} 

之後。當responseData準備就緒時,會調用委託方法。比在變量responseData中進行輪詢還有更好的解決方案嗎?

回答

0

您的代理人不必是一個單獨的類。

- (void)someMethod:(NSUrl *)url 
{ 
    ASIHTTPRequest *req = [ASIHTTPRequest requestWithUrl:url]; 
    [req setDelegate:self]; 
    //configure the request 
    [req startAsynchronous]; 
} 

- (void)requestDone:(ASIHTTPRequest *)request 
{ 
    NSString *response = [request responseString]; 
    //do whatever with the response 
} 

所以你的方法someMethod:火災的請求,並返回void。當請求完成後,您ASIHTTPRequest觸發它的代表,這是此相同的對象requestDone:方法。在這種方法中,你可以做任何事情 - 設置ivar或命名屬性,處理傳入的數據並填充UITableVew,無論如何。

注意ASIHTTPRequest現在已經過時了,它的作者建議使用別的東西來代替。 AFNetworking似乎是一種流行的選擇,但我最近還沒有開始一個新項目,所以我自己還沒有選擇一個。

0

你絕對不應該做投票!

您設置爲自會調用一個方法(請參閱該委託方法的細節ASIHTTPRequest文檔)在結束時再通知你,ASIHHTPRequest的代表。在該委託方法中,請調用您想要執行的其他任何代碼。不要擔心返回圖像 - 它都是異步的。

+0

我瞭解代表。那麼,我該如何編寫一個實現這種方法的獨立類?我必須以某種方式返回。 – 2012-02-21 12:20:04

+0

你爲什麼要回來?只需將代表團添加到您的班級。如果您使用異步調用編寫代碼,則必須相應地調整編碼和設計。 – 2012-02-21 12:23:34

1

我用ASIHttpRequest對於大多數我的Web服務調用,但在你的情況(獲得的圖像數據異步),我使用的塊與GCD。我有一個類叫做WebImageOperations和I類有一個類方法:

WebImageOperations.h:

+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage; 

WebImageOperations.m:

+ (void)processImageDataWithURLString:(NSString *)urlString andBlock:(void (^)(NSData *imageData))processImage 
{ 
    NSURL *url = [NSURL URLWithString:urlString]; 

    dispatch_queue_t callerQueue = dispatch_get_current_queue(); 
    dispatch_queue_t downloadQueue = dispatch_queue_create("com.achcentral.processimagedataqueue", NULL); 
    dispatch_async(downloadQueue, ^{ 
     NSData * imageData = [NSData dataWithContentsOfURL:url]; 

     dispatch_async(callerQueue, ^{ 
      processImage(imageData); 
     }); 
    }); 
    dispatch_release(downloadQueue); 
} 

然後調用它,使用:

[WebImageOperations processImageDataWithURLString:@"MyURLForPicture" andBlock:^(NSData *imageData) { 
     if (self.view.window) { 
      UIImage *image = [UIImage imageWithData:imageData]; 
      self.myImageView.image = image; 
     } 
}];