打开摄像头拍照更换图片, 并保存到沙盒及本地相册, 还有直接从图库选择图片以及一系列的权限判断与跳转

在vc中
先引入一个头文件, 用于ios9下判断是否有访问系统相册权限

#import <Photos/Photos.h>

先签这俩协议

@interface NAMinePicModifyViewController ()< UIImagePickerControllerDelegate, UINavigationControllerDelegate>

写个属性

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

写个懒加载, 避免重复创建

- (UIImagePickerController *)imagePickerController{
    if (!_imagePickerController) {
    _imagePickerController = [[UIImagePickerController alloc] init];
    _imagePickerController.delegate = self;
    
    //模态推出照相机页面的样式
    _imagePickerController.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    _imagePickerController.allowsEditing = YES;
    }
return _imagePickerController;
}

在一个拍照触发按钮点击事件, cell点击事件也行,

#pragma mark - 选择拍照
- (void)selectImageFromCamera{

    //判断相机是否可用
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
    
    //判断是否开启相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    
    //权限未开启
    if (authStatus == AVAuthorizationStatusRestricted || authStatus == AVAuthorizationStatusDenied)
    {
        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{

        self.imagePickerController.delegate = self;
        self.imagePickerController.allowsEditing = YES;
        self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:self.imagePickerController animated:YES completion:^{}];
    }
}
//适用于没有相机的设备
else{

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

    #pragma mark - 让alert自动消失
     [NSTimer scheduledTimerWithTimeInterval:2 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 - ImagePicker delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{

    [picker dismissViewControllerAnimated:YES completion:^{
    
    
    }];

    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    /* 此处info 有六个值
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    //保存图片至本地
    [self saveImage:image withName:@"currentImage.png"];

    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
    UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

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

    //用拍下来的照片赋值
    [_headerView.buttonOfIcon setImage:savedImage forState:UIControlStateNormal];


    //访问相册权限, ios9之后的api, 要引入<Photos/Photos.h>
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

    //相册权限已开启
    if(status == PHAuthorizationStatusAuthorized){
    
        //存入本地相册
        UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    
}

//未开启相册权限
//PHAuthorizationStatusNotDetermined,
//PHAuthorizationStatusRestricted
//PHAuthorizationStatusDenied
    else{

        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];

}

}

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

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

}

#pragma mark - 保存图片至沙盒
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{

    if (UIImagePNGRepresentation(currentImage)) {
    
   data = UIImagePNGRepresentation(currentImage);
    
}else{
    
   data = UIImageJPEGRepresentation(currentImage, 1.0);
    
}

    //获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];

    //将图片写入文件
    //atomically:这个参数意思是如果为YES则保证文件的写入原子性,就是说会先创建一个临时文件,直到文件内容写入成功再导入到目标文件里.如果为NO,则直接写入目标文件里
    [data writeToFile:fullPath atomically:NO];

}

在视图类中, 对每次程序启动进行判断

#pragma mark - 确保每次运行都是上次修改后的照片
//读取图片
NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
UIImage *savedImage = [[UIImage alloc] initWithContentsOfFile:fullPath];

//本地有的话直接读取沙盒本地
if (savedImage) {
    [_buttonOfIcon setImage:savedImage forState:UIControlStateNormal];
}
//没有的话是默认初始图片
else{
    [_buttonOfIcon setImage:[UIImage imageNamed:@"sendPhoto"] forState:UIControlStateNormal];
}

调用系统相册、相机发现是英文的系统相簿界面后标题显示“photos”,但是手机语言已经设置显示中文,纠结半天,最终在info.plist设置解决问题

info.plist里面添加Localized resources can be mixed YES

表示是否允许应用程序获取框架库内语言。

最后 感谢http://my.oschina.net/joanfen/blog/134677

--------------------我是分割线----------------------------------
此处感谢http://www.xuanyusong.com/archives/1493
接下来说打开本地相册选取图片

pragma mark - 选择打开本地图库

- (void)openLocalAlbum{

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

}

再配合之前写的

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info

方法即可, 如果已经写了, 则不用再写一遍, 也不用分开判断

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,088评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,715评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,361评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,099评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 60,987评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,063评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,486评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,175评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,440评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,518评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,305评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,190评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,550评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,880评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,152评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,451评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,637评论 2 335

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,043评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,943评论 4 60
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,490评论 18 139
  • 今天的读书会主题是:从弗洛伊德这杯酒中品人格心理学。一个小时的学习与分享在愉快的阅读体验中不知不觉地结束了。深奥的...
    筱箖2017阅读 232评论 0 0
  • 在上一篇文章中,Jason老师提到名词从句在句子中可以做主语、宾语和补语。 今天,Jason老师继续带大家了解名词...
    JasonEnglish阅读 545评论 0 0