用Photos框架保存图片到相册

用Photos框架保存图片到相册_第1张图片
图片来自500px

文 || 張贺

一、保存图片到相机胶卷(Camera Roll)

方法一:利用C语言函数(最快速、最简单的方法)
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *Photo;
@end
@implementation ViewController
//保存照片到相册
- (IBAction)savePhoto {
    // Adds a photo to the saved photos album.  The optional completionSelector should have the form:
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    //只能保存到相机胶卷(不能保存到自定义相册)
    UIImageWriteToSavedPhotosAlbum(self.Photo.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (error) {
        //保存失败
    }else{
        //保存成功
    }
}
@end

以上代码运行后程序崩溃。
错误信息:

This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSPhotoLibraryUsageDescription key with a string value explaining to the user how the app uses this data.

意思是需要在Info.plist里面增加NSPhotoLibraryUsageDescription这个key来询问用户是否允许访问相册,value为string "我要窥探你的隐私啦~"

用Photos框架保存图片到相册_第2张图片
示例程序运行截图
方法二:AssetsLibrary框架(iOS9以后废弃,使用Photos框架替代)
方法三:Photos框架

Photos框架须知:
1、PHAsset : 一个PHAsset对象就代表相册中的一张图片或者视频
查 : [PHAsset fetchAsset...]
增删改 :PHAssetChangeRequest(包括图片/视频相关的所有改动操作)
2、PHAssetCollection : 一个PHAssetCollection对象就代表一个相册
查 : [PHAssetCollection fetchAssetCollections...]
增删改 :PHAssetCollectionChangeRequest(包括相册相关的所有改动操作)
3、对相片/相册的任何 [增删改] 操作都必须放到以下两个block中去执行
-[PHPhotoLibrary performChanges:completionHandler:]
-[PHPhotoLibrary performChangesAndWait:error:]
代码:
#import "ViewController.h"
#import
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *Photo;
@end
@implementation ViewController
//保存照片到相册
- (IBAction)savePhoto {

    //保存照片到相机胶卷
    //异步执行修改操作
    //PHPhotoLibrary对象就代表着Photos这个应用
    [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
        //默认就把相片保存到了相机胶卷
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.Photo.image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            //保存失败
        }else{
            //保存成功
        }
    }];

    NSError *error = nil;
    //保存照片到相机胶卷
    //同步执行修改操作
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        //默认就把相片保存到了相机胶卷
        [PHAssetChangeRequest creationRequestForAssetFromImage:self.Photo.image];
} error:&error];

    if (error) {
        //保存失败
    }else{
        //保存成功
    }
}
@end

二、保存图片到自定义相册

第一步:保存图片到相机胶卷
第二步:拥有一个自定义相册
方法一:AssetsLibrary框架(iOS9以后废弃,使用Photos框架替代)
方法二:Photos框架
#import "ViewController.h"
#import 
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *Photo;
@end
@implementation ViewController
//创建一个自定义相册
- (IBAction)createdCollection {
    //获取应用的名字
    NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
    //抓取所有的自定义相册(保证相册只被创建一个)
    PHFetchResult *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    //查找当前APP对应的自定义相册
    PHAssetCollection *createdCollection = nil;
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:title]) {
            createdCollection = collection;
            break;
        }
    }
    //当前APP对应的自定义相册没有被创建过
    if (createdCollection == nil) {
        NSError *error = nil;
        __block NSString *createdCollectionID;
        [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
            //创建一个相册,拿到相册的唯一标识符
            createdCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
    
        //根据相册的唯一标识符拿到相册
        createdCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionID] options:nil].firstObject;
        if (error) {
            //保存失败
        }else{
            //保存成功
        }
    }
}
@end
第三步:添加刚才保存的图片到自定义相册
方法一:AssetsLibrary框架(iOS9以后废弃,使用Photos框架替代)
方法二:Photos框架
//保存照片到自定义相册
- (void)saveImageIntoAlbum{
    //保存图片到相机胶卷
    PHFetchResult *createdAsset = self.createdAsset;
    if (createdAsset == nil) {
        //保存照片失败
        return;
    }
    //获得相册
    PHAssetCollection *collection = self.createdCollection;
    if (collection == nil) {
        //创建相册失败
        return;
    }
    //把刚才添加到相机胶卷的照片放到自定义相册
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
        [request insertAssets:createdAsset atIndexes:[NSIndexSet indexSetWithIndex:0]]; 
    } error:&error];
    if (error) {
        //保存图片失败
        return;
    }
}
用Photos框架保存图片到相册_第3张图片
添加图片到自定义的相册

获取以上代码全文点这里

你可能感兴趣的:(用Photos框架保存图片到相册)