拍照与从相册取照片(重新捋一遍逻辑)

之前写过, 觉得有些逻辑不是很妥当, 重写一篇

引入这个是为了访问相册, 存储拍照后的图片

#import <Photos/Photos.h>

签协议

@interface ViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>

声明属性

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

先说用户选择拍照的情况, 涉及判断用户设备是否有相机, 是否允许使用相机, imagePickerController属性可以写懒加载, 因为都是取单张照片, 没必要每次都开辟空间, 但如果是取多张照片, 建议不要这么玩, 前面说过不再说

#pragma mark - 选择拍照
- (void)goTakePic:(UIButton *)button{

    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    
        //判断是否开启相机权限
        AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        //权限未开启
        if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied){
            [self userDidNotAllowCamera];
        }
    
        //权限已开启
        else{
    
            _imagePickerController = [[UIImagePickerController alloc] init];
            _imagePickerController.delegate = self;
            //模态推出照相机页面的样式
            _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
            _imagePickerController.allowsEditing = YES;
            self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.imagePickerController animated:YES completion:^{}];
        }
    }
    //适用于没有相机的设备
    else{
        [self userDidnotHaveCamera];
    }
}

#pragma mark - 用户没有相机
- (void)userDidnotHaveCamera{

    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"相机不可用" preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:alertController animated:YES completion:nil];

//让alert自动消失
    [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(creatAlert:) userInfo:alertController repeats:NO];
}

#pragma mark 让警告消失
- (void)creatAlert:(NSTimer *)timer{

    UIAlertController *alert = [timer userInfo];
    [alert dismissViewControllerAnimated:YES completion:nil];
    alert = nil;
}

#pragma mark 用户没有允许相机权限
- (void)userDidNotAllowCamera{

    if ([UIDevice currentDevice].systemVersion.floatValue < 10){
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"您尚未开启相机权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //info plist中URL type中添加一个URL Schemes添加一个prefs值
        if([[UIApplication sharedApplication] canOpenURL:url]){
            //跳转到隐私
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=CAMERA"]];
        }
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"不了" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionOK];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
else{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"抱歉" message:@"您尚未开启相机权限" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
}

================我是分割线=======================

接下来是选择去相册选择照片的情况, 其实和拍照差不多, 也就这句不一样,

self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

#pragma mark - 选择去相册
- (void)goToAlbum:(UIButton *)button{

    _imagePickerController = [[UIImagePickerController alloc] init];

    //去相册才会有效果
    _imagePicker.navigationBar.barTintColor = kRGBColor(0, 148, 255);
    //按钮字体颜色
    _imagePicker.navigationBar.tintColor = [UIColor whiteColor];
    //title字体大小和颜色
    [[UINavigationBar appearance] setTitleTextAttributes:@{
                                                           NSForegroundColorAttributeName:[UIColor whiteColor],
                                                           NSFontAttributeName:[UIFont systemFontOfSize:16 * SCALE_WIDTH]
                                                           }];

    //模态推出照相机页面的样式
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;

    self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePickerController.delegate = self;
    //设置选择后的图片可被编辑
    self.imagePickerController.allowsEditing = YES;
    [self presentViewController:self.imagePickerController animated:YES completion:^{}];
}

====================分割线再次降临================
接下来是图片获取之后的协议方法, 拍照和相册共用这个协议方法, 所以加个判断, 如果是拍照才把拍后的图片存到相册, 从相册取就不用存了

注意, 可编辑要在协议方法里配合
[info objectForKey:UIImagePickerControllerEditedImage];
编辑后的图片才会生效

#pragma mark - ImagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //原图
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];

    //这个本来是想用于拍照后编辑的, 发现并没有用
    //self.isFullScreen = NO;

    //用拍下来的照片赋值
    _imageViewOfPic.image = image;

    //只有选择拍照才会把照片保存到相册
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
    
        //访问相册权限, ios9之后的api, 要引入<Photos/Photos.h>
        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
        //未开启相册权限
        //PHAuthorizationStatusNotDetermined,
        //PHAuthorizationStatusRestricted
        //PHAuthorizationStatusDenied
        if(status == PHAuthorizationStatusDenied){
        
            [self userDidnotAllowAlbum];
        }else{
            //存入本地相册
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
        }
    }

    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark 存储到系统相册结果回调
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{

    if (error){
        NSLog(@"%@", error);
    }
    else{
        NSLog(@"保存成功");
    }
}

#pragma mark 用户不允许使用相册
- (void)userDidnotAllowAlbum{

   if ([UIDevice currentDevice].systemVersion.floatValue < 10){
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您尚未开启相册权限" message:@"无法存入所拍的照片" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *actionOK = [UIAlertAction actionWithTitle:@"去开启" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        //info plist中URL type中添加一个URL Schemes添加一个prefs值
        if([[UIApplication sharedApplication] canOpenURL:url]){
            //跳转到隐私
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=Privacy&path=PHOTOS"]];
        }
    }];
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"不了" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionOK];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
else{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"您尚未开启相册权限" message:@"无法存入所拍的照片" preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *actionCancel = [UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleDefault handler:nil];
    [alertController addAction:actionCancel];
    [self presentViewController:alertController animated:YES completion:nil];
}
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,393评论 5 467
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 83,790评论 2 376
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,391评论 0 330
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,703评论 1 270
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,613评论 5 359
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,003评论 1 275
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,507评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,158评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,300评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,256评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,274评论 1 328
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,984评论 3 316
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,569评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,662评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,899评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,268评论 2 345
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,840评论 2 339

推荐阅读更多精彩内容