【问题标题】:writeToFile: returning correct path, but no file?writeToFile:返回正确的路径,但没有文件?
【发布时间】:2015-06-23 21:02:13
【问题描述】:

我有这段代码可以从我为 NSImage 获得的 NSData 制作 PNG,但在 Downloads 文件夹中没有创建文件?

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

}

【问题讨论】:

    标签: nsdata nsurl writetofile cgimageref nsbitmapimagerep


    【解决方案1】:

    需要:

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

    因为我试图写入路径,但返回的是 URL,所以如果您首先在那里创建文件,您只能写入路径。

    【讨论】:

    • 能否请您 edit 解释为什么这段代码回答了这个问题?纯代码答案是 discouraged,因为它们不教授解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-04-12
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多