照片库使用单例发来请求授权 或者 查询授权状态
单例
+ (PHPhotoLibrary *)sharedPhotoLibrary;
获取授权状态
+ (PHAuthorizationStatus)authorizationStatus;
请求授权
+ (void)requestAuthorization:(void(^)(PHAuthorizationStatus status))handler;
同时注册照片库改变的观察者,接受到改变后执行照片库的观察者代理协议
#pragma mark - Change Handling
- (void)registerChangeObserver:(id<PHPhotoLibraryChangeObserver>)observer;
- (void)unregisterChangeObserver:(id<PHPhotoLibraryChangeObserver>)observer;
@protocol PHPhotoLibraryChangeObserver <NSObject>
- (void)photoLibraryDidChange:(PHChange *)changeInstance;
@end
保存图片方式
// 保存到相册
- (void)savePhotoToAlbum:(UIImage*)image
completionBlock:(nullable void (^)(WBPKPhoto *photo,NSError *error))completionBlock {
@autoreleasepool {
__block PHObjectPlaceholder *assetPlaceholder = nil;
dispatch_semaphore_wait(self.savePhotoToAlbumSemaphore, DISPATCH_TIME_FOREVER);
[[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
PHAssetChangeRequest *changeRequest = [PHAssetChangeRequest creationRequestForAssetFromImage:image];
assetPlaceholder = changeRequest.placeholderForCreatedAsset;
} completionHandler:^(BOOL success, NSError * _Nullable error) {
PHFetchResult *result = nil;
if (success && assetPlaceholder) {
result = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetPlaceholder.localIdentifier] options:nil];
WBPKPhoto *photo = [[WBPKPhoto alloc] initWithPHAsset:result.firstObject];
if (completionBlock) completionBlock(photo,error);
} else {
if (completionBlock) completionBlock(nil,error);
}
dispatch_semaphore_signal(self.savePhotoToAlbumSemaphore);
}];
}
}
网友评论