2013-02-20 63 views
1

我想寫一個便捷函數,將接受圖像標識符並使​​用AFNetworking的AFImageRequestOperation下載圖像。該函數正確下載圖像,但是我無法返回成功塊中的UIImage。從AFImageRequestOperation成功塊返回圖像

-(UIImage *)downloadImage:(NSString*)imageIdentifier 
{ 
    NSString* urlString = [NSString stringWithFormat:@"http://myserver.com/images/%@", imageIdentifier]; 

    AFImageRequestOperation* operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] imageProcessingBlock:nil 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) 
    { 
    NSLog(@"response: %@", response); 
    return image;             
    } 
    failure:nil]; 

[operation start]; 

} 

return image;行給我的錯誤:

Incompatible block pointer types sending 'UIImage *(^)(NSURLRequest *__strong, NSHTTPURLResponse *__strong, UIImage *__strong)' to parameter of type 'void (^)(NSURLRequest *__strong, NSHTTPURLResponse *__strong, UIImage *__strong)' 

發生了什麼事的任何想法?我很想能夠只是調用

UIImage* photo = [downloadImage:id_12345];

回答

3

AFNetworking圖像下載操作是異步的,你不能在工作開始的點分配給它。

您正在嘗試構建的函數應使用委託或塊。

- (void)downloadImageWithCompletionBlock:(void (^)(UIImage *downloadedImage))completionBlock identifier:(NSString *)identifier { 
    NSString* urlString = [NSString stringWithFormat:@"http://myserver.com/images/%@", identifier]; 

    AFImageRequestOperation* operation = [AFImageRequestOperation imageRequestOperationWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] imageProcessingBlock:nil 
    success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) 
    { 
    NSLog(@"response: %@", response); 
    completionBlock(image);             
    } 
    failure:nil]; 

    [operation start]; 
} 

這樣稱呼它

// start updating download progress UI 
[serverInstance downloadImageWithCompletionBlock:^(UIImage *downloadedImage) { 
    myImage = downloadedImage; 
    // stop updating download progress UI 
} identifier:@""];