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

该问题纠结了我半天时间。。。查了很多资料,最后才发现调用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;

}

希望能帮助大家解决问题哈~

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容