2013-10-21 143 views
51

似乎沒有AFImageRequestOperation,但只有AFImageResponseSerializer坦率地說,我不明白它,或者我只是通過AFNetworking網站看起來太長...下載圖像與以前的AFNetworking就像一個魅力。我討厭回到較老的AFnetworking,因爲我通過新版本做了幾乎所有的東西......任何人?如何使用AFNetworking 2.0下載圖像?

回答

126

所以你想爲2.0這樣的東西。

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; 
requestOperation.responseSerializer = [AFImageResponseSerializer serializer]; 
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Response: %@", responseObject); 
    _imageView.image = responseObject; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Image error: %@", error); 
}]; 
[requestOperation start]; 

正如亞當提到你也可以做類似下面的,如果你只是想要把它扔進一個ImageView的

[myImageView setImageWithURL:[NSURL URLWithString:@"http://sitewithimage.com/images/myimage.png"]]; 
+3

拯救了我的生命:)我知道有一些解決方案:) – raistlin

+0

這將在主隊列或背景隊列? – Tander

+0

@Tander完成塊在主隊列上運行 – Bot

4

老版本,沒有responseSerializer,你也可以

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest]; 
//requestOperation.responseSerializer = [AFImageResponseSerializer serializer]; 
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
    NSLog(@"Response: %@", responseObject); 
    _imageView.image = [UIImage imageWithData:responseObject]; 

} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
    NSLog(@"Image error: %@", error); 
}]; 
[requestOperation start]; 
+0

這個問題是特定於AFNetworking 2.0 – Bot

+0

好吧,你是對的。 – lbsweek

0

對於斯威夫特使用AFNetworking人,above solution可以寫成下面

let requestOperation : AFHTTPRequestOperation = AFHTTPRequestOperation(request: urlRequest) 
    requestOperation.responseSerializer = AFImageResponseSerializer() 

    requestOperation.setCompletionBlockWithSuccess({ (requestOperation, responseObject) in 
     print(responseObject) 
     _imageView.image = responseObject as? UIImage 

    }) { (requestOperation, error) in 
     print(error) 
    } 
    requestOperation.start() 
相關問題