如何将UIImage上传到Documents中的特定文件夹?

时间:2011-07-15 08:23:54

标签: iphone objective-c ios

我有一个图像名称(比如@“image.jpg”),我想将它保存到我在我的Documents文件夹中创建的名为“coffeeShops”的文件夹中。我怎么能这样做?

1 个答案:

答案 0 :(得分:2)

NSString *docs = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *dir = @"coffeeShops";
NSString *destPath = [docs stringByAppendingPathComponent:dir];

// check if the destination directory exists, if not create it
BOOL isDirectory;
BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:destPath isDirectory:&isDirectory];
if(!exists || !isDirectory) {
    NSError *error = nil;
    [[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
    if(error != nil) {
        // should do error checking here
        NSLog(@"%@",[error localizedDescription]);
    }
}

NSString *fileName = @"image.jpg";
NSString *path = [destPath stringByAppendingPathComponent:fileName];

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