配置权限
参考: 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.photoLibrary
if(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 = self
imagePickerController.allowsEditing = true//true为拍照、选择完进入图片编辑模式
imagePickerController.sourceType = sourceType
self.present(imagePickerController, animated: true, completion: {
})
}
}
//取消
func imagePickerControllerDidCancel(_ picker:UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}
// UIImagePickerControllerDelegate,UINavigationControllerDelegate
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let userAvatar = info[UIImagePickerControllerEditedImage] as! UIImage
self.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
}
}