在实现访问相册和拍照功能之前需要先询问用户以获取权限,这就需要在info.plist里面写入
Privacy - Camera Usage Description
Privacy - Photo Library Usage Description
如图所示
String的后面填入提示框要显示的文字
上述步骤完成后,在需要访问相册和拍照功能的页面导入包和添加代理
import AVFoundation
import Photos
UIActionSheetDelegate
UIImagePickerControllerDelegate
UINavigationControllerDelegate
实现如下方法
//点击按钮
@IBAction func editHeadImgButton(_ sender: AnyObject) {
let actionSheet = UIActionSheet.init(title: nil, delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil, otherButtonTitles: "拍照", "从相册选取")
actionSheet.show(in: self.view)
}
//选择进入相册或拍照
func actionSheet(_ actionSheet: UIActionSheet, clickedButtonAt buttonIndex: Int) {
if buttonIndex == 1 {
self.takePhoto()
} else if buttonIndex == 2 {
self.infoImage()
}
}
//从相册
func infoImage() {
//判断有无打开相册的权限
if self.PhotoLibraryPermissions() {
let imagePicker = UIImagePickerController.init()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
imagePicker.modalTransitionStyle = UIModalTransitionStyle.coverVertical
imagePicker.allowsEditing = true
//进入相册
self.navigationController?.present(imagePicker, animated: true, completion: nil)
} else {
UIAlertView.init(title: "提示", message: "请在设置中打开相册权限", delegate: nil, cancelButtonTitle: "确定").show()
}
}
//拍照
func takePhoto() {
//判断有无打开照相机的权限
if self.cameraPermissions() {
let imagePicker = UIImagePickerController.init()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerControllerSourceType.camera
imagePicker.modalTransitionStyle = UIModalTransitionStyle.coverVertical
imagePicker.allowsEditing = true
//打开照相机
self.navigationController?.present(imagePicker, animated: true, completion: nil)
} else {
UIAlertView.init(title: "提示", message: "请在设置中打开摄像头权限", delegate: nil, cancelButtonTitle: "确定").show()
}
}
其中判断权限的方法如下
//判断相机访问权限
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
}
}
获取到图片之后会触发代理方法
//图片选择后
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info["UIImagePickerControllerEditedImage"] as! UIImage
//如果是拍照的图片
if picker.sourceType == UIImagePickerControllerSourceType.camera {
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}
//这就是你要的图片
print(image)
self.dismiss(animated: true, completion: nil)
}