如何将<应用程序中的图片>保存到<手机相册>中
三大步骤
/*
1.添加图片到【相机胶卷】
1> UIImageWriteToSavedPhotosAlbum函数
2> AssetsLibrary框架
3> Photos框架(推荐)
2.拥有一个【自定义相册】
1> AssetsLibrary框架
2> Photos框架(推荐)
3.将刚才添加到【相机胶卷】的图片,引用(添加)到【自定义相册】
1> AssetsLibrary框架
2> Photos框架(推荐)
*/
Photos框架须知
/*
Photos框架须知
1.PHAsset : 一个PHAsset对象代表一张图片或者一个视频文件
1> 负责查询一堆的PHAsset对象
2.PHAssetCollection : 一个PHAssetCollection对象代表一个相册
1> 负责查询一堆的PHAssetCollection对象
3.PHAssetChangeRequest
1> 负责执行对PHAsset的【增删改】操作
2> 这个类只能放在-[PHPhotoLibrary performChanges:completionHandler:] 或者 -[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
4.PHAssetCollectionChangeRequest
1> 负责执行对PHAssetCollection的【增删改】操作
2> 这个类只能放在-[PHPhotoLibrary performChanges:completionHandler:] 或者 -[PHPhotoLibrary performChangesAndWait:error:]方法的block中使用
*/
//当用户点击"保存图片"的按钮时
-(IBAction )save {
/*
requestAuthorization方法的功能
1.如果用户还没有做过选择,这个方法就会弹框(是否允许该程序访问相册)让用户做出选择
1> 用户做出选择以后才会回调block
2.如果用户之前已经做过选择,这个方法就不会再弹框,直接回调block,传递现在的授权状态给block
*/
PHAuthorizationStatus oldStatus = [PHPhotoLibrary authorizationStatus];
//此方法在异步线程调用
NSLog(@"%@",[NSThread currentThread]);
//将和UI相关的东西放在主线程去做
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
dispatch_async(dispatch_get_main_queue(), ^{
switch (status) {
case PHAuthorizationStatusAuthorized: {
// 保存图片到相册
[self saveImageIntoAlbum];
break;
}
case PHAuthorizationStatusDenied: {
if (oldStatus == PHAuthorizationStatusNotDetermined) return;
XMGLog(@"提醒用户打开相册的访问开关")
break;
}
case PHAuthorizationStatusRestricted: {
[SVProgressHUD showErrorWithStatus:@"因系统原因,无法访问相册!"];
break;
}
default:
break;
}
});
}];
/**
* 获得刚才添加到【相机胶卷】中的图片
*/
- (PHFetchResult<PHAsset *> *)createdAssets
{
__block NSString *createdAssetId = nil;
// 添加图片到【相机胶卷】
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
createdAssetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
} error:nil];
if (createdAssetId == nil) return nil;
// 在保存完毕后取出图片
return [PHAsset fetchAssetsWithLocalIdentifiers:@[createdAssetId] options:nil];
}
/**
* 获得【自定义相册】
*/
- (PHAssetCollection *)createdCollection
{
// 获取软件的名字作为相册的标题
NSString *title = [NSBundle mainBundle].infoDictionary[(NSString *)kCFBundleNameKey];
// 获得所有的自定义相册
PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collections) {
if ([collection.localizedTitle isEqualToString:title]) {
return collection;
}
}
// 代码执行到这里,说明还没有自定义相册
__block NSString *createdCollectionId = nil;
// 创建一个新的相册
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
createdCollectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
} error:nil];
if (createdCollectionId == nil) return nil;
// 创建完毕后再取出相册
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createdCollectionId] options:nil].firstObject;
}
/**
* 保存图片到相册
*/
- (void)saveImageIntoAlbum
{
// 获得相片
PHFetchResult<PHAsset *> *createdAssets = self.createdAssets;
// 获得相册
PHAssetCollection *createdCollection = self.createdCollection;
if (createdAssets == nil || createdCollection == nil) {
[SVProgressHUD showErrorWithStatus:@"保存失败!"];
return;
}
// 将相片添加到相册
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
[request insertAssets:createdAssets atIndexes:[NSIndexSet indexSetWithIndex:0]];
} error:&error];
// 保存结果
if (error) {
[SVProgressHUD showErrorWithStatus:@"保存失败!"];
} else {
[SVProgressHUD showSuccessWithStatus:@"保存成功!"];
}
}
常见的BUG
This method can only be called from inside of -[PHPhotoLibrary performChanges:completionHandler:] or -[PHPhotoLibrary performChangesAndWait:error:]
// Asynchronously 异步执行操作
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
XMGLog(@"保存完毕")
}];
// Synchronously 同步执行操作
NSError *error = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
[PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image];
} error:&error];
//注意:PHPhotoLibrary的performChangesAndWait的block不能嵌套的,因为这个方法是同步方法,这样会卡主线程造成死锁
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
} error:nil];
} error:nil];
其他注意细节
// 这个方法只适合加载普通的plist文件,不能用来加载Info.plist
[NSDictionary dictionaryWithContentsOfFile:pathForResource:]
CoreFoundation和Foundation之间的数据类型,可以互相转换
只有遵守了NSFastEnumeration协议的对象才能使用for-in循环
/* 自动生成的内容:number的getter声明+实现、_number成员变量*/
@property (nonatomic, assign, readonly) NSInteger number;