iOS 授权相册保存图片(iOS 8及之后)

需要引入的头文件

//相册
#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(@"成功保存到相册")
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,475评论 25 709
  • 刚看完几集 欢乐颂。 挺羡慕刘涛和奇点在见面之前的交流方式,不知道对方性别、年龄、通讯方式等一些富有主观因素的外在...
    盐小茴香阅读 1,430评论 0 0
  • 泰国之行,从青岛流亭机场出发,后到达韩国,从韩国转机到泰国。在离开的这几天里,唯一担心的就是儿子,早晨看到...
    风中的玫瑰花阅读 1,397评论 0 1
  • Quoted from the interview:Grace Hopper on Letterman(https...
    Norman_Plus阅读 1,670评论 0 0