我们分为几个步骤学习
准备工作
- 配置info.plist
- 引入头文件
在开始开发之前需要进行info.plist的配置,如果不进行配置会抛错。
<key>NSPhotoLibraryUsageDescription</key>
<string>使用相册存储图片</string>
2019-12-23 09:13:56.301622+0800 ZucheDemo[920:649891] [access] 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.
在开发之前我们导入头文件
#import <Photos/Photos.h>
存储一个图片到相册胶卷
此方法可以保存一张图片到相机胶卷。
/// 保存图片到相机胶卷
- (void)saveImageToCameraRoll:(UIImage *)image {
//保存图片到【相机胶卷】
[[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
//异步执行修改操作
[PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
if (error) {
NSLog(@"%@",@"保存失败");
} else {
NSLog(@"%@",@"保存成功");
}
}];
}
创建一个相册(以应用名册命名)
首先我们看如何创建一个相册
/// 创建以app名字命名的相册
- (void)createNewCollection {
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
//获取app名字
NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
//创建一个【自定义相册】
[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
} error:&error];
}
但是这么简单的创建相册,一般不符合需求,一般我们需要先查看是否已经存在同名相册。
/// 查看是否创建了以APP命名的相册
- (PHAssetCollection *)checkLocalCollection {
NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
return [self checkCollection:title];
}
/// 查看是否创建了以此名字命名的相册
/// @param title 相册名字
- (PHAssetCollection *)checkCollection:(NSString *)title {
//查询所有【自定义相册】
PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
PHAssetCollection *createCollection = nil;
for (PHAssetCollection *collection in collections) {
if ([collection.localizedTitle isEqualToString:title]) {
createCollection = collection;
break;
}
}
return createCollection;
}
所以我们需要先查看是否存在同名相册,之后再进行创建相册
/// 创建一个以APP名字命名的相册,如果不存在
- (void)createNewCollectionIfNotExist {
NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString*)kCFBundleNameKey];
PHAssetCollection *createCollection = [self checkCollection:title];
if (createCollection == nil) {
//当前对应的app相册没有被创建
//创建一个【自定义相册】
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
//创建一个【自定义相册】
[PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title];
} error:&error];
}
}
保存图片到创建的相册
/// 保存图片到自己创建的相册
/// @param image 图片
- (void)savePhotoToAlbum:(UIImage *)image {
// 1.先保存图片到【相机胶卷】
/// 同步执行修改操作
NSError *error = nil;
__block PHObjectPlaceholder *placeholder = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
placeholder = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
} error:&error];
if (error) {
NSLog(@"保存失败");
return;
}
// 2.查看是否拥有一个以APP名称命名的相册
PHAssetCollection * assetCollection = [self checkLocalCollection];
if (assetCollection == nil) {
NSLog(@"获取相册失败");
return;
}
// 3.将刚才保存到【相机胶卷】里面的图片引用到【自定义相册】
[[PHPhotoLibrary sharedPhotoLibrary]performChangesAndWait:^{
PHAssetCollectionChangeRequest *requtes = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
[requtes addAssets:@[placeholder]];
} error:&error];
if (error) {
NSLog(@"保存图片失败");
} else {
NSLog(@"保存图片成功");
}
}
查找图片并显示
/// 查找图片
- (void)fetchPhotoFromLocalCollection {
PHAssetCollection *assetCollection = [self checkLocalCollection];
if (assetCollection == nil) {
NSLog(@"获取相册失败");
return;
}
PHFetchResult *results = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
if (results.count > 0) {
__weak typeof(self) weakSelf = self;
//获取最后一个图片
PHAsset *asset = results.lastObject;
//获取显示图片控件的大小
CGSize size = CGSizeMake(CGRectGetWidth(self.imageView.bounds), CGRectGetHeight(self.imageView.bounds));
//调用转换方法
[self imageWithAsset:asset size:size resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (result) {
NSLog(@"%@",info);
weakSelf.imageView.image = result;
}
else {
NSLog(@"转换图片失败");
}
}];
}
}
/// asset转成为image
/// @param asset asset description
/// @param size 图片尺寸
/// @param resultHandler 结果回调
- (void)imageWithAsset:(PHAsset *)asset size:(CGSize)size resultHandler:(void(^)(UIImage * _Nullable result, NSDictionary * _Nullable info))resultHandler {
//option的设置
PHImageRequestOptions *option = [[PHImageRequestOptions alloc] init];
option.resizeMode = PHImageRequestOptionsResizeModeNone;
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:(PHImageContentModeAspectFit) options:option resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
if (resultHandler) {
resultHandler(result,info);
}
}];
}
从相册中删除图片
/// 删除图片
- (void)deletePhotoFromLocalCollection {
PHAssetCollection *assetCollection = [self checkLocalCollection];
PHFetchResult *results = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
if (results.count > 0) {
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
//删除时候需要传入一个PHFetchResulth或者一个数组,遵守这个协议的类<NSFastEnumeration>
//删除最后一张
//[PHAssetChangeRequest deleteAssets:@[results.lastObject]];
//删除整个相册内的所有图片
[PHAssetChangeRequest deleteAssets:results];
} error:&error];
}
}