nsdatansurlwritetofilecgimagerefnsbitmapimagerep

writeToFile: returning correct path, but no file?


I have this code to make a PNG out of NSData I have for an NSImage, but no file is created in the Downloads folder?

- (IBAction)saveToDownloadsFolder:(id)sender {

    NSInteger selected = [tvContent selectedRow];
    ImageCell *selectedRow = [tvContent viewAtColumn:0 row:selected makeIfNecessary:YES];

    NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDownloadsDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];

    CGImageRef CGImage = [selectedRow.item.image CGImageForProposedRect:nil context:nil hints:nil];
    NSBitmapImageRep *rep = [[[NSBitmapImageRep alloc] initWithCGImage:CGImage] autorelease];
    NSDictionary* imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1] forKey:NSImageCompressionFactor];
    NSData *data = [rep representationUsingType: NSPNGFileType properties:imageProps];
    [data writeToFile:[NSString stringWithFormat:@"%@", [documentsURL URLByAppendingPathComponent:@"Copyfeed-Image.png"]] atomically:YES];


    NSLog(@"URL %@", [NSString stringWithFormat:@"%@", [documentsURL URLByAppendingPathComponent:@"Copyfeed-Image.png"]]);

}

Solution

  • Needed to be:

    [data writeToURL:[documentsURL URLByAppendingPathComponent:@"Copyfeed-Image.png"] atomically:YES];
    

    Because I was trying to write to a path, but was returning a URL, you can only write to path it seems if you first create a file there.