將圖片寫入系統(tǒng)相冊
/**
保存圖片到系統(tǒng)相薄
*/
- (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(@"=========保存圖片成功");
}
}];
}
將圖片寫入系統(tǒng)相冊和相薄
- (void)saveImageToPhotoLibrary
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.listModel.originalUrls[_currentIndex]]];
UIImage *image = [UIImage imageWithData:data]; // 取得圖片
//保存圖片
__block NSString *assetId = nil;
// 1. 存儲圖片到"相機(jī)膠卷"
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 新建一個(gè)PHAssetCreationRequest對象
// 返回PHAsset(圖片)的字符串標(biāo)識
assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
// 2. 獲得相冊對象
PHAssetCollection *collection = [self getCollection];
// 3. 將“相機(jī)膠卷”中的圖片添加到新的相冊
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
NSLog(@"%@", [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil]);
// 根據(jù)唯一標(biāo)示獲得相片對象
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
// 添加圖片到相冊中
[request addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
NSLog(@"成功保存到相簿:%@", collection.localizedTitle);
[MBProgressHUD showSuccessMessage:@"保存圖片成功"];
}];
}];
}
- (PHAssetCollection *)getCollection {
// 先獲得之前創(chuàng)建過的相冊
PHFetchResult<PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *collection in collectionResult) {
if ([collection.localizedTitle isEqualToString:@"搜緣"]) {
return collection;
}
}
// 如果相冊不存在,就創(chuàng)建新的相冊(文件夾)
__block NSString *collectionId = nil; // __block修改block外部的變量的值
// 這個(gè)方法會在相冊創(chuàng)建完畢后才會返回
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
// 新建一個(gè)PHAssertCollectionChangeRequest對象, 用來創(chuàng)建一個(gè)新的相冊
collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:@"搜緣"].placeholderForCreatedAssetCollection.localIdentifier;
} error:nil];
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}