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

在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

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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