本文自作自用筆記,不喜勿噴,誠謝糾錯。
調用相機首先需要設置info.plist文件獲取相機訪問權限。http://www.cnblogs.com/lc901221/p/6599644.html
調用時需要遵守兩個協議UIImagePickerControllerDelegate和UINavigationControllerDelegate。
下面貼出調用相機的代碼:
let imagePicker = UIImagePickerController()
//檢測相機是否可用
let isAvailable = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera)
//必須首先設置sourceType 然后再設置其他屬性 否則會出異常,提示sourceType 必須是 UIImagePickerControllerSourceTypeCamera
imagePicker.sourceType = .photoLibrary
if isAvailable {
imagePicker.sourceType = .camera
//如果有前置攝像頭則調用前置攝像頭
imagePicker.cameraDevice = UIImagePickerControllerCameraDevice.front
//是否顯示控制欄,這里選擇false會展示系統相機UI,如果要自定義可以將其隱藏
imagePicker.showsCameraControls=false
}
//代理
imagePicker.delegate = self
//打開相機
present(imagePicker, animated: true, completion: {
})
//是否可編輯
imagePicker.allowsEditing=false
下面是比較有用的兩個協議方法:
//獲取當前相機拍攝的照片,確定時的回調
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
self.dismiss(animated: true, completion: nil)
if let photo = info[UIImagePickerControllerOriginalImage] as! UIImage?{
let image = UIImageView.init(frame: self.view.frame)
self.view.addSubview(image)
image.image = photo
}
}
//點擊系統自定義取消按鈕的回調
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.dismiss(animated: true, completion: nil)
}