Ignacio Oroná Ignacio Oroná - 4 months ago 23
iOS Question

iOS Block image return

So I am working on a project and I must use AFImageDownloader in order to download some images that we need to use in our project. I use the following code:

-(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");
}];
}


The delegate is of course not nil and code of the updateImageWithImage is:

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


So basically when I try to get the UIImage I get it as a response and assign it to the UICollectionViewCell and it crashes! I guess that I should do some kind of "copy" of the responseObject before using it in order parts of my program, but I am not really sure what the problem is. Any ideas?

Answer

I figured it out. I was basically using AFImagedownloader wrong, this is the proper way to use this Class:

[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!!!");

                               }];