保存到本地的方式
1.UIImageWriteToSavedPhotosAlbum 函数
缺点: 只能保存图片,不能拿到图片的标示符引用到其他相册
UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}
//无论图片保存成功或失败,都会来到这个方法
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
}
2.Photos.framework - 从iOS8开始可以使用,可以完全取AssetsLibrary.framework
Photos.framework使用注意:
1.PHAsset : 一个PHAsset对象代表相册中的一张图片或者一段视频
2.PHAssetCollection : 一个PHAssetCollection对象代表一个相册
3.PHAssetChangeRequest : 利用这个对象能添加,删除,修改PHAsset对象
4.PHAssetCollectionChangeRequest : 利用这个对象能添加、删除、修改PHAssetCollection对象
5.对相片\相册的任何改动操作,都必须放在以下方法的block中
1> -[PHPhotoLibrary performChanges:completionHandler:]
2> -[PHPhotoLibrary performChangesAndWait:error:]
#import <Photos/Photos.h>
- (void)saveImage
{
NSError *error = nil;
//先拿到图片的占位标示符
__block NSString *assetId = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
assetId = [PHAssetChangeRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier;
} error:&error];
//通过占位标示符拿到图片数组;后面再引用到相册
PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil];
// 获得App的名称
NSString *title = [NSBundle mainBundle].infoDictionary[(__bridge NSString *)kCFBundleNameKey];
PHAssetCollection *createdCollection = nil;
//先获取手机里面有没有该相册
PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collections) {
if ([collection.localizedTitle isEqualToString:title]) {
createdCollection = collection;
break;
}
}
// 没有该相册,自己创建一个;同样也是先获取占位标示符
if (createdCollection == nil) {
// 创建【自定义相册】
__block NSString *collectionId = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:title].placeholderForCreatedAssetCollection.localIdentifier;
} error:&error];
//通过占位标示符拿到对应相册
createdCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
//创建一个修改相册的请求
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createdCollection];
//添加图片到相册第一个位置
[request insertAssets:assets atIndexes:[NSIndexSet indexSetWithIndex:0]];
} error:&error];
// 提示
if (error) {
[SVProgressHUD showErrorWithStatus:@"保存失败!"];
} else {
[SVProgressHUD showSuccessWithStatus:@"保存成功!"];
}
}
3.AssetsLibrary.framework - 从iOS9开始废弃