我正在使用UIImagePickerController来使用我的相机,代码如下:
@objc func toggle() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
//Define UIImagePickerController variable
let imagePicker = UIImagePickerController()
//Assign the delegate
imagePicker.delegate = self
//Set image picker source type
imagePicker.sourceType = .camera
//Allow Photo Editing
imagePicker.allowsEditing = true
//Present camera
UIApplication.topViewController()?.present(imagePicker, animated: true, completion: nil)
}
}
现在我正在尝试捕获使用didFinishPickingMediaWithInfo方法拍摄的图像,我在网上找到了这个示例:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let imageUrl = info[UIImagePickerControllerOriginalImage] as! NSURL
let imageName = imageUrl.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!)
let image = info[UIImagePickerControllerOriginalImage]as! UIImage
let data = UIImagePNGRepresentation(image)
do
{
try data?.write(to: localPath!, options: Data.WritingOptions.atomic)
}
catch
{
// Catch exception here and act accordingly
}
UIApplication.topViewController()?.dismiss(animated: true, completion: nil);
}
我将UIImagePickerControllerReferenceURL更改为UIImagePickerControllerOriginalImage,因为UIImagePickerControllerReferenceURL为nil。但是在我更改后,我遇到了以下致命错误:
无法将类型为“UIImage”(0x1b6b02b58)的值转换为“NSURL”
我该如何保存从相机拍摄的图像?我做错了什么?
UIImagePickerControllerImageURL
不是 info 中的一个键。 - user979331