Search code examples
objective-cuiimageafnetworkingafnetworking-2

Saving image from url to disk not working


I'm trying to download an image from an url in my app, so that it can be used by the Today Extension.

So I call [self downloadImageFromUrl:imageOne];, which uses this method:

- (void)downloadImageFromUrl:(NSString *)url {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];

    AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    requestOperation.responseSerializer = [AFImageResponseSerializer serializer];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSURL *storeUrl = [fileManager containerURLForSecurityApplicationGroupIdentifier:@"group.myapp.TodayExtensionDefaults"];
        NSString *path = [storeUrl absoluteString];
        path = [path stringByAppendingPathComponent:@"Test/imageOne.png"];

        NSLog(@"Path is %@", path);

        NSLog(@"Response: %@", responseObject);
        UIImage *image = responseObject;

        [UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

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

    [requestOperation start];
}

So when I run this, everything executes fine. I get no errors. Yet, when I go to the folder logged in the simulator, no file is present. The error I get from the write action is Write returned error: The operation couldn’t be completed. (Cocoa error 4.). And so I changed the write action to:

if (![[NSFileManager defaultManager] fileExistsAtPath:path]) {
    NSError *error = nil;
    if (![[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&error]) {
        NSLog(@"Error: %@. %s, %i", error.localizedDescription, __PRETTY_FUNCTION__, __LINE__);
    }
}

[UIImagePNGRepresentation(image) writeToFile:path options:NSDataWritingAtomic error:&error];

But I still get Write returned error: The operation couldn’t be completed. (Cocoa error 4.)


Solution

  • You are grabbing the absoluteString (which includes the scheme, amongst other things):

    NSString *path = [storeUrl absoluteString];
    

    I believe you intended the path:

    NSString *path = [storeUrl path];