这是我使用/选择的完整代码
// MARK: Camera App
func openCameraApp() {
if UIImagePickerController.availableCaptureModes(for: .rear) != nil {
picker.allowsEditing = false
picker.sourceType = UIImagePickerControllerSourceType.camera
picker.cameraCaptureMode = .photo
picker.modalPresentationStyle = .fullScreen
present(picker,
animated: true,
completion: nil)
} else {
noCamera()
}
}
func noCamera(){
let alertVC = UIAlertController(
title: "No Camera",
message: "Sorry, this device has no camera",
preferredStyle: .alert)
let okAction = UIAlertAction(
title: "OK",
style:.default,
handler: nil)
alertVC.addAction(okAction)
present(
alertVC,
animated: true,
completion: nil)
}
// MARK: Photos Albums
func showImagePicker() {
picker.allowsEditing = false
picker.sourceType = .photoLibrary
//picker.modalPresentationStyle = .Popover
present(picker,
animated: true,
completion: nil)
picker.popoverPresentationController?.sourceView = self.view
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage
image = chosenImage
self.performSegue(withIdentifier: "ShowEditView", sender: self)
dismiss(animated: true, completion: nil)
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
dismiss(animated: false, completion: nil)
}
// MARK: Seque to EditViewController
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ShowEditView" {
if let vc = segue.destination as? EditViewController {
vc.image = image
//vc.image = images[0]
}
}
}
忽略两个注释掉的行 - 这些是我的测试东西。此代码适用于所有设备、iOS 9+、所有方向(但请记住,iPhone 始终显示为纵向),而且我在模拟器(它没有摄像头)和物理设备中都没有遇到任何问题。
有趣的是可能导致问题的一件事(不确定它是否会引发 SIGABRT) - 我正在检查后置摄像头并在它不存在时发出警报。 (不过没有检查前置摄像头。我什至不确定除了 iPod touch 是否没有前置摄像头。)
另外,不要忘记在 iOS 10 的 info.plist 中添加两件事:
<key>NSCameraUsageDescription</key>
<string>Used to capture new image for photo effect</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Used to select an image for photo effect</string>
你可以在描述标签中放任何你想要的东西。如果没有这些,应用程序将在 iOS 10 中关闭,Apple 将拒绝您的提交。 Here's 更多详情的链接。