需要引入的头文件
//相册
#import <Photos/Photos.h>
授权相册代码
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
}]
typedef NS_ENUM(NSInteger, PHAuthorizationStatus) {
PHAuthorizationStatusNotDetermined = 0, // 用户还没有做出选择
PHAuthorizationStatusRestricted, // 家长控制,不允许访问
PHAuthorizationStatusDenied, //用户拒绝当前应用访问相册,我们需要提醒用户打开访问开关
PHAuthorizationStatusAuthorized // 用户允许当前应用访问相册
} PHOTOS_AVAILABLE_IOS_TVOS(8_0, 10_0);
示例
[PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
UIAlertController *openPH = [UIAlertController alertControllerWithTitle:@"提示" message:@"无访问相册权限,是否去打开权限" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *suerAction = [UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
}
}];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[openPH addAction:suerAction];
[openPH addAction:cancelAction];
[self presentViewController:openPH animated:YES completion:nil];
}else {
//要插入相册的图片
UIImage *tempImage = [self getScreenImage];
UIImageWriteToSavedPhotosAlbum(tempImage, self, @selector((image:didFinishSavingWithError:contextInfo:)), (__bridge void *)self);
}
}];
保存照片后的回调
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
if (error) {
NSLog(@"保存相册失败,请使用右上角分享尝试")
}else {
NSLog(@"成功保存到相册")
}
}
网友评论