如何将图像保存到iOS 9.0中的特定文件夹中

时间:2015-11-09 07:19:08

标签: ios objective-c alassetslibrary ios9.1 phphotolibrary

已经有了使用 ALAssetsLibrary 将图像保存到特定文件夹的答案。但它在iOS 9.0中已被弃用并发出警告“使用Photos框架中的PHPhotoLibrary”

当我将ALAssetsLibrary更改为PHPhotoLibrary时,此时会收到错误。

    [self.library saveImage:image toAlbum:@"myAlbum" withCompletionBlock:^(NSError *error) {
    if (error!=nil) {
        NSLog(@"Big error: %@", [error description]);
    }
}];

*误差

 No visible @interface for 'PHPhotoLibrary' declares the selector 'saveImage:toAlbum:withCompletionBlock:' 

如何将图像保存到特定文件夹中使用 PHPhotoLibrary (或)任何其他解决方案。

提前谢谢。

2 个答案:

答案 0 :(得分:3)

我还没有使用过PHPhotoLibrary但是我知道使用本地文档目录在Obj-C中保存照片的老派方式:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths.firstObject;
NSData *imageData = UIImagePNGRepresentation(image);

NSString *imagePath = [NSString stringWithFormat:@"%@/%@",documentsDirectory,imageFolder];

BOOL isDir;
NSFileManager *fileManager= [NSFileManager defaultManager];
if(![fileManager fileExistsAtPath:imagePath isDirectory:&isDir])
    if(![fileManager createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:NULL])
        NSLog(@"Error: folder creation failed %@", documentsDirectory);

[[NSFileManager defaultManager] createFileAtPath:[NSString stringWithFormat:@"%@/%@", imagePath, imageName] contents:nil attributes:nil];
[imageData writeToFile:[NSString stringWithFormat:@"%@/%@", imagePath, imageName] atomically:YES];

从NSDocumentDirectory中检索该图像:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = paths.firstObject;
NSString *fullPath = [NSString stringWithFormat:@"%@/%@", documentDirectory, imagePath]; // image path is same as above
if ([[NSFileManager defaultManager] fileExistsAtPath:fullPath]) {
    UIImage *image = [UIImage imageWithContentsOfFile:fullPath];
    return image;
} else {
    return nil;
}

答案 1 :(得分:0)

因为没有像这样命名的方法。

要将图像保存到PHPhotoLibrary,您需要创建一个资产。见

Which PHAssetCollection to use for saving an image?

详细信息。