美文网首页
iOS view保存到本地相册

iOS view保存到本地相册

作者: coco_CC | 来源:发表于2021-03-31 21:15 被阅读0次
/// 调方法保存到本地相册
[self p_savePhoto];
- (void)p_savePhoto {
    
    // 获取当前应用对照片的访问授权状态
       if ([PHPhotoLibrary authorizationStatus] != PHAuthorizationStatusAuthorized) {
           self.timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(observeAuthrizationStatusChange:) userInfo:nil repeats:YES];
       }
    [self p_saveImageOrPhoto];
}

//self.savePhone 保存到本地的view
- (void)p_saveImageOrPhoto {
    
    //保存图片到【相机胶卷】
        /// 异步执行修改操作
    UIImage *image = [self yj_convertCreateImageWithUIView: self.savePhone];
        [[PHPhotoLibrary sharedPhotoLibrary]performChanges:^{
            
            [PHAssetChangeRequest creationRequestForAssetFromImage:image];
            
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (error) {
                NSLog(@"%@",@"保存失败");
                [error.userInfo objectForKey:@"NSLocalizedDescription"];
                if ([error.domain containsString:@"Photos Access not allowed (authorization status 2)"]) {
                    [SVProgressHUD showSuccessWithStatus:@"保存失败,请开启访问相册权限"];
                }
                
            } else {
                NSLog(@"%@",@"保存成功");
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
            }
        }];
}

- (void)observeAuthrizationStatusChange:(NSTimer *)timer
{
    /** 当用户已授权 */
    if ([PHPhotoLibrary authorizationStatus] == PHAuthorizationStatusAuthorized) {
        [timer invalidate];
        self.timer = nil;
        [self p_saveImageOrPhoto];
    }
}

/**
 将 UIView 转换成 UIImage

 @param view 将要转换的View
 @return 新生成的 UIImage 对象
 */
- (UIImage *)yj_convertCreateImageWithUIView:(UIView *)view{

    UIGraphicsBeginImageContextWithOptions(view.frame.size, YES, [UIScreen mainScreen].scale);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
//    NSData *imageData = UIImageJPEGRepresentation(image,1.0f);

    return image;
}

相关文章

网友评论

      本文标题:iOS view保存到本地相册

      本文链接:https://www.haomeiwen.com/subject/aewahltx.html