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(NSDocumentDirectoryNSUserDomainMask, 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)