iOS Block图片返回

时间:2016-07-20 21:31:38

标签: ios afnetworking objective-c-blocks

所以我正在开发一个项目,我必须使用AFImageDownloader才能下载我们需要在项目中使用的一些图像。我使用以下代码:

-(void) downloadImage:(NSURL*) url
{
    AFHTTPSessionManager *sessionManager = [[AFHTTPSessionManager alloc] init];
    AFImageDownloader    *imgDownloader = [[AFImageDownloader alloc] initWithSessionManager:sessionManager downloadPrioritization:AFImageDownloadPrioritizationFIFO maximumActiveDownloads:1 imageCache:nil];    
    AFHTTPResponseSerializer *responseSerializer = [AFHTTPResponseSerializer serializer];
    responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json",@"binary/octet-stream",nil];
    sessionManager.responseSerializer = responseSerializer;
    NSURLRequest *req = [NSURLRequest requestWithURL:url];
    [imgDownloader downloadImageForURLRequest:req success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *responseObject){
        self.image = responseObject;
        [self.delegate updateImageWithImage:self.image]; // ** CRASH **

    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
        NSLog(@"Error");
    }];
}

委托当然不是 nil ,而且updateImageWithImage的代码是:

-(void) updateImageWithImage:(UIImage*) img {
   self.image.image = img;
}

所以基本上当我尝试获取UIImage时,我将其作为响应并将其分配给UICollectionViewCell并且崩溃了!我想我应该做一些"复制"在我的程序部分使用它之前responseObject,但我不确定问题是什么。有什么想法吗?

1 个答案:

答案 0 :(得分:-1)

我明白了。我基本上使用AFImagedownloader错了,这是使用这个类的正确方法:

[self.imageView setImageWithURLRequest:jpegURLRequest

                      placeholderImage:placeholder

                                   success:^(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image){

                                       NSLog(@"Success");



                                       completionBlock(image);

                                   }

                               failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {

                                   NSLog(@"ERROR!!!");

                               }];