You have a few problems here. so first, why are you using @autoreleasepool
? i think there is no need for this here. also, are you using ARC? i consider this, for the rest of my answer.
in AFNetworking there is a class called AFImageRequestOperation
, so this would be a good idea for you to use. first, import it
#import "AFImageRequestOperation.h"
then you could create an object
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];
AFImageRequestOperation *operation;
operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
cacheName:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
now, in the success block, you got the UIImage you need.
there you need to get the documents directory. your code will not work on an ios device.
// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];
and then you could use NSDatas writeToFile
// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];
at last, you need to start the operation
[operation start];
all together:
- (void)downloadImageInBackground:(NSDictionary *)args{
NSString *guideName = [args objectForKey:@"guideName"];
NSString *photourl = [args objectForKey:@"photoUrl"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:photourl]];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request
imageProcessingBlock:nil
cacheName:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
// Get dir
NSString *documentsDirectory = nil;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
NSString *pathString = [NSString stringWithFormat:@"%@/%@",documentsDirectory, guideName];
// Save Image
NSData *imageData = UIImageJPEGRepresentation(image, 90);
[imageData writeToFile:pathString atomically:YES];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", [error localizedDescription]);
}];
[operation start];
}