您的位置:首页 > 移动开发 > IOS开发

ios 调用writeToFile将图片保存到本地一直失败的解决方案

2015-06-19 11:27 621 查看
该问题纠结了我半天时间。。。查了很多资料,最后才发现调用writeToFile返回false的原因。在此附上解决方案:

NSData *imageData =
UIImageJPEGRepresentation(currentImage,
1.0f);//currentImage是传过来的UIImage
NSString *inewImageName=[self
getImagePath:imageName];//imageName为图片名称
BOOL operation = [imageData
writeToFile:newImageName options:NSAtomicWrite
error:&error];

方法:

- (NSString*)getImagePath:(NSString *)name {
    NSArray *path =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES);
    NSString *docPath = [path
objectAtIndex:0];
    NSFileManager *fileManager = [NSFileManager
defaultManager];
    NSString *finalPath = [docPath
stringByAppendingPathComponent:name];
    
    // Remove the filename and create the remaining path
    [fileManager createDirectoryAtPath:[finalPath
stringByDeletingLastPathComponent]
withIntermediateDirectories:YES
attributes:nil
error:nil];//stringByDeletingLastPathComponent是关键
    
    return finalPath;
}
希望能帮助大家解决问题哈~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ios path 图片 解决方案