将图片写入系统相册
/**
保存图片到系统相薄
*/
- (void)saveImageToSystemPhotoLibrary
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.listModel.originalUrls[_currentIndex]]];
UIImage *image = [UIImage imageWithData:data]; // 取得图片
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
//写入图片到相册
PHAssetChangeRequest *req = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
NSLog(@"success = %d, error = %@", success, error);
if (success)
{
NSLog(@"=========保存图片成功");
}
}];
}
将图片写入系统相册和相薄
- (void)saveImageToPhotoLibrary
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.listModel.originalUrls[_currentIndex]]];
UIImage *image = [UIImage imageWithData:data]; // 取得图片
//保存图片
__block NSString *assetId = nil;
// 1. 存储图片到"相机胶卷"
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 新建一个PHAssetCreationRequest对象
// 返回PHAsset(图片)的字符串标识
assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
// 2. 获得相册对象
PHAssetCollection *collection = [self getCollection];
// 3. 将“相机胶卷”中的图片添加到新的相册
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
NSLog(@"%@", [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil]);
// 根据唯一标示获得相片对象
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
// 添加图片到相册中
[request addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
NSLog(@"成功保存到相簿:%@", collection.localizedTitle);
[MBProgressHUD showSuccessMessage:@"保存图片成功"];
}];
}];
}
- (PHAssetCollection *)getCollection {
// 先获得之前创建过的相册
PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collectionResult) {
if ([collection.localizedTitle isEqualToString:@"搜缘"]) {
return collection;
}
}
// 如果相册不存在,就创建新的相册(文件夹)
__block NSString *collectionId = nil; // __block修改block外部的变量的值
// 这个方法会在相册创建完毕后才会返回
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
// 新建一个PHAssertCollectionChangeRequest对象, 用来创建一个新的相册
collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"搜缘"].placeholderForCreatedAssetCollection.localIdentifier;
} error:nil];
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}