自定義相冊(cè)
- 第一首先創(chuàng)建一個(gè)管理相片的單列類 (必須導(dǎo)入相冊(cè)對(duì)應(yīng)的類庫(kù)
@import Photos;
@import UIKit;
)
注:collection.localizedTitle 相薄名字
- 需要定義必要的一些屬性和回調(diào)Block。
typedef void(^PHAssetCollectionBlock)(NSMutableArray <PHAssetCollection *> * collections);
typedef void(^PHAssetPhotoBlock)(NSMutableArray <PHAsset *> * photos);
typedef void(^PHImgBlock)(UIImage * images);
@property (nonatomic,strong) NSMutableArray<PHAssetCollection*>* collections; //存放所有相薄
-(instancetype)init
{
if (self = [super init])
{
self.collections = [NSMutableArray arrayWithCapacity:0];
}
return self;
}
+(instancetype)shareInstance
{
static RTPhotoManager * photoManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
photoManager = [[RTPhotoManager alloc]init];
});
return photoManager;
}
/**
獲得所有的自定義相簿和獲得相機(jī)膠卷
@param successBlock 成功是回調(diào)的block
*/
-(void)openPhotosCollectionSuccess:(PHAssetCollectionBlock)successBlock {
// 獲得所有的自定義相簿
PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
// 獲得相機(jī)膠卷
PHAssetCollection *cameraRoll = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil].lastObject;
[self.collections addObject:cameraRoll];
for (PHAssetCollection *assetCollection in assetCollections) {
[self.collections addObject:assetCollection];
}
successBlock(self.collections);
}
/**
遍歷相簿中的所有圖片資源
@param assetCollection 相簿
@param synchronous 是否同步
@param successBlock 成功是回調(diào)的block
*/
- (void)enumerateAssetsInAssetCollection:(PHAssetCollection *)assetCollection isSynchronous:(BOOL)synchronous Success:(PHAssetPhotoBlock)successBlock {
PHImageRequestOptions *options = [[PHImageRequestOptions alloc] init];
// 同步獲得圖片, 只會(huì)返回1張圖片
options.synchronous = synchronous;
// 獲得某個(gè)相簿中的所有PHAsset對(duì)象
PHFetchResult<PHAsset *> *assets = [PHAsset fetchAssetsInAssetCollection:assetCollection options:nil];
NSMutableArray *assetPhotos = [[NSMutableArray alloc]init];
for (PHAsset *asset in assets) {
[assetPhotos addObject:asset];
}
successBlock(assetPhotos);
}
/**
從圖片資源獲得圖片Image
@param asset 圖片資源
@param successBlock 成功是回調(diào)的block
@param isThumbnail 是否要縮略圖
*/
- (void)getImagesFromPHAsset:(PHAsset*)asset Success:(PHImgBlock)successBlock isGetThumbnailImage:(BOOL)isThumbnail
{
CGSize size = CGSizeZero;
if (!isThumbnail) {
size =CGSizeMake(asset.pixelWidth, asset.pixelHeight);
}
[[PHImageManager defaultManager] requestImageForAsset:asset targetSize:size contentMode:PHImageContentModeDefault options:nil resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
successBlock(result);
}];
}
static PHImageRequestOptions *requestOptions;
if (!requestOptions) {
requestOptions = [[PHImageRequestOptions alloc] init];
//指定請(qǐng)求是否同步執(zhí)行边器。
requestOptions.synchronous = YES;
// 圖像質(zhì)量客蹋。有三種值:Opportunistic揣云,在速度與質(zhì)量中均衡;HighQualityFormat峰搪,不管花費(fèi)多長(zhǎng)時(shí)間糜值,提供高質(zhì)量圖像;FastFormat忠烛,以最快速度提供好的質(zhì)量属提。 這個(gè)屬性只有在 synchronous 為 true 時(shí)有效。normalizedCropRect:用于對(duì)原始尺寸的圖像進(jìn)行裁剪,基于比例坐標(biāo)冤议。只在 resizeMode 為 Exact 時(shí)有效斟薇。
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeOpportunistic;
//對(duì)請(qǐng)求的圖像怎樣縮放。有三種選擇:None恕酸,不縮放堪滨;Fast,盡快地提供接近或稍微 大 于要求的尺寸尸疆;Exact椿猎,精準(zhǔn)提供要求的尺寸
requestOptions.resizeMode =PHImageRequestOptionsResizeModeNone;
}
[[PHImageManager defaultManager] requestImageDataForAsset:asset options:requestOptions resultHandler:^(NSData * _Nullable imageData, NSString * _Nullable dataUTI, UIImageOrientation orientation, NSDictionary * _Nullable info) {
[UIImage imageWithData:imageData];
}];
利用UIImagePickerController挑選圖片
// UIImagePickerController : 可以從系統(tǒng)自帶的App(照片\\\\相機(jī))中獲得圖片// 判斷相冊(cè)是否可以打開
if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return;
UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
// 打開照片應(yīng)用(顯示所有相簿)
ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
// 打開照片應(yīng)用(只顯示"時(shí)刻"這個(gè)相簿)
// ipc.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
// 照相機(jī)
// ipc.sourceType = UIImagePickerControllerSourceTypeCamera;ipc.delegate = self;
[self presentViewController:ipc animated:YES completion:nil];
#pragma mark - <UIImagePickerControllerDelegate>
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
// 銷毀控制器
[picker dismissViewControllerAnimated:YES completion:nil];
// 設(shè)置圖片 self.imageView.image = info[UIImagePickerControllerOriginalImage];
}
NaN錯(cuò)誤- 錯(cuò)誤起因:0被當(dāng)做除數(shù), 比如 10 / 0## 最簡(jiǎn)單的方法保存圖片到相機(jī)膠卷
UIImageWriteToSavedPhotosAlbum(self.imageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
/** * 通過(guò)UIImageWriteToSavedPhotosAlbum函數(shù)寫入圖片完畢后就會(huì)調(diào)用這個(gè)方法
* * @param image 寫入的圖片
* @param error 錯(cuò)誤信息
* @param contextInfo UIImageWriteToSavedPhotosAlbum函數(shù)的最后一個(gè)參數(shù) */
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
if (error) {
[SVProgressHUD showErrorWithStatus:@"圖片保存失敗!"];
} else {
[SVProgressHUD showSuccessWithStatus:@"圖片保存成功!"];
}
}
保存圖片到自定義相冊(cè)
- (void)save {
/* PHAuthorizationStatusNotDetermined,
用戶還沒有做出選擇 PHAuthorizationStatusDenied,
用戶拒絕當(dāng)前應(yīng)用訪問(wèn)相冊(cè)(用戶當(dāng)初點(diǎn)擊了"不允許") PHAuthorizationStatusAuthorized
用戶允許當(dāng)前應(yīng)用訪問(wèn)相冊(cè)(用戶當(dāng)初點(diǎn)擊了"好") PHAuthorizationStatusRestricted,
因?yàn)榧议L(zhǎng)控制, 導(dǎo)致應(yīng)用無(wú)法方法相冊(cè)(跟用戶的選擇沒有關(guān)系) */
// 判斷授權(quán)狀態(tài) PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus]; if (status == PHAuthorizationStatusRestricted) {
// 因?yàn)榧议L(zhǎng)控制, 導(dǎo)致應(yīng)用無(wú)法方法相冊(cè)(跟用戶的選擇沒有關(guān)系)
[SVProgressHUD showErrorWithStatus:@"因?yàn)橄到y(tǒng)原因, 無(wú)法訪問(wèn)相冊(cè)"];
} else if (status == PHAuthorizationStatusDenied) {
// 用戶拒絕當(dāng)前應(yīng)用訪問(wèn)相冊(cè)(用戶當(dāng)初點(diǎn)擊了"不允許") XMGLog(@"提醒用戶去[設(shè)置-隱私-照片-xxx]打開訪問(wèn)開關(guān)");
} else if (status == PHAuthorizationStatusAuthorized) {
// 用戶允許當(dāng)前應(yīng)用訪問(wèn)相冊(cè)(用戶當(dāng)初點(diǎn)擊了"好")
[self saveImage];
} else if (status == PHAuthorizationStatusNotDetermined) {
// 用戶還沒有做出選擇 // 彈框請(qǐng)求用戶授權(quán)
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { if (status == PHAuthorizationStatusAuthorized) { // 用戶點(diǎn)擊了好 [self saveImage];
} }];
}}
- (void)saveImage{
// PHAsset : 一個(gè)資源, 比如一張圖片\\\\一段視頻
// PHAssetCollection : 一個(gè)相簿
// PHAsset的標(biāo)識(shí), 利用這個(gè)標(biāo)識(shí)可以找到對(duì)應(yīng)的PHAsset對(duì)象(圖片對(duì)象) _
_block NSString *assetLocalIdentifier = nil;
// 如果想對(duì)"相冊(cè)"進(jìn)行修改(增刪改), 那么修改代碼必須放在[PHPhotoLibrary sharedPhotoLibrary]的performChanges方法的block中
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 1.保存圖片A到"相機(jī)膠卷"中 // 創(chuàng)建圖片的請(qǐng)求
assetLocalIdentifier = [PHAssetCreationRequest creationRequestForAssetFromImage:self.imageView.image].placeholderForCreatedAsset.localIdentifier; } completionHandler:^(BOOL success, NSError * _Nullable error) { if (success == NO) { [self showError:@"保存圖片失敗!"];
return;
}
// 2.獲得相簿
PHAssetCollection *createdAssetCollection = [self createdAssetCollection]; if (createdAssetCollection == nil) { [self showError:@"創(chuàng)建相簿失敗!"];
return;
}
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
// 3.添加"相機(jī)膠卷"中的圖片A到"相簿"D中
// 獲得圖片
PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetLocalIdentifier] options:nil].lastObject;
// 添加圖片到相簿中的請(qǐng)求
PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest
changeRequestForAssetCollection:createdAssetCollection];
// 添加圖片到相簿 [request addAssets:@[asset]];
} completionHandler:^(BOOL success, NSError * _Nullable error) {
//分線程
if (success == NO) { [self showError:@"保存圖片失敗!"];;
} else { [self showSuccess:@"保存圖片成功!"];; } }]; }];}
/** * 獲得相簿 */
- (PHAssetCollection *)createdAssetCollection{
// 從已存在相簿中查找這個(gè)應(yīng)用對(duì)應(yīng)的相簿
PHFetchResult<PHAssetCollection *> *assetCollections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
for (PHAssetCollection *assetCollection in assetCollections) {
if ([assetCollection.localizedTitle isEqualToString:XMGAssetCollectionTitle]) { return assetCollection; } }
// 沒有找到對(duì)應(yīng)的相簿, 得創(chuàng)建新的相簿
// 錯(cuò)誤信息 NSError *error = nil;
// PHAssetCollection的標(biāo)識(shí), 利用這個(gè)標(biāo)識(shí)可以找到對(duì)應(yīng)的PHAssetCollection對(duì)象(相簿對(duì)象)
__block NSString *assetCollectionLocalIdentifier = nil;
[[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
// 創(chuàng)建相簿的請(qǐng)求
assetCollectionLocalIdentifier = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:XMGAssetCollectionTitle].placeholderForCreatedAssetCollection.localIdentifier; } error:&error];
// 如果有錯(cuò)誤信息 if (error) return nil;
// 獲得剛才創(chuàng)建的相簿
return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[assetCollectionLocalIdentifier] options:nil].lastObject;}
- (void)showSuccess:(NSString *)text{
dispatch_async(dispatch_get_main_queue(), ^{ [SVProgressHUD showSuccessWithStatus:text]; });
}
- (void)showError:(NSString *)text{
dispatch_async(dispatch_get_main_queue(), ^{ [SVProgressHUD showErrorWithStatus:text];
});
}