本文主要是介绍iOS10 拍照打开相册选择图片,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
配置权限
参考: http://blog.csdn.net/riven_wn/article/details/60771097
重要说明
在使用相机或相册的之前最好进行系统权限判断, 如果相机权限用户未允许,会出现打开相机无法拍照的情况,相册权限关闭的情况下,会有个系统的默认提示,但用户体验都不算太好。首先要先做以下步骤
1.引入 AVFoundation.framework
2.导入头文件 import AVFoundation 、 import Photos
然后进行判断判断之后如果发现用户关闭了权限,可弹出 alert 告诉用户跳转到当前应用的系统设置里进行开启
访问相册或相机获取图片
开始之前应遵循以下几个代理 UIImagePickerControllerDelegate,UIActionSheetDelegate,UINavigationControllerDelegate
这里我直接跳转了,用的时候你可以在跳转之前加个 alert
//访问相册func visitAlbum() {var sheet:UIActionSheet?if(UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)){sheet = UIActionSheet(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "从相册选择","拍照")}else {sheet = UIActionSheet(title:nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "从相册选择")}sheet!.show(in: self.view)}//选取图片func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {//选取图片var sourceType = UIImagePickerControllerSourceType.photoLibraryif(buttonIndex != 0){//相册if(buttonIndex==1){if(!PhotoLibraryPermissions()) {//跳转至系统设置UIApplication.shared.openURL(NSURL(string:UIApplicationOpenSettingsURLString)! as URL)}sourceType = UIImagePickerControllerSourceType.photoLibrary}else{if(!cameraPermissions()) {UIApplication.shared.openURL(NSURL(string:UIApplicationOpenSettingsURLString)! as URL)}sourceType = UIImagePickerControllerSourceType.camera}let imagePickerController:UIImagePickerController = UIImagePickerController()imagePickerController.delegate = selfimagePickerController.allowsEditing = true//true为拍照、选择完进入图片编辑模式imagePickerController.sourceType = sourceTypeself.present(imagePickerController, animated: true, completion: {})}}//取消func imagePickerControllerDidCancel(_ picker:UIImagePickerController) {self.dismiss(animated: true, completion: nil)}// UIImagePickerControllerDelegate,UINavigationControllerDelegatefunc imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {let userAvatar = info[UIImagePickerControllerEditedImage] as! UIImageself.dismiss(animated: true, completion: nil)//显示在界面上 或上传图片self.xibView.imgView.image = userAvatar}//判断相机权限func cameraPermissions() -> Bool{let authStatus:AVAuthorizationStatus = AVCaptureDevice.authorizationStatus(forMediaType: AVMediaTypeVideo)if(authStatus == AVAuthorizationStatus.denied || authStatus == AVAuthorizationStatus.restricted) {return false}else {return true}}//判断相册权限func PhotoLibraryPermissions() -> Bool {let library:PHAuthorizationStatus = PHPhotoLibrary.authorizationStatus()if(library == PHAuthorizationStatus.denied || library == PHAuthorizationStatus.restricted){return false}else {return true}}
这篇关于iOS10 拍照打开相册选择图片的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!