I am facing difficulties storing an image taken from the camera when using UIImagePickerController and getting its URL.
Checking the logs, I think it's because the taken image has no saved path on phone?
let imageUrl = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
...
let localPath = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)
I wonder how I can fix this? I have consulted other answers but none of them work (deprecated libraries or other issues).
More complete code:
func openCamera() {
if UIImagePickerController.isSourceTypeAvailable(.camera) {
let imagePickerController = UIImagePickerController()
imagePickerController.delegate = self
imagePickerController.sourceType = .camera;
imagePickerController.allowsEditing = false
present(imagePickerController, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
guard let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage else {
fatalError("error message")
}
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
let imageUrl = info[UIImagePickerControllerImageURL] as? NSURL // logs show nil here
let imageName = imageUrl?.lastPathComponent
let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
let photoURL = NSURL(fileURLWithPath: documentDirectory)
let localPath = photoURL.appendingPathComponent(imageName!) // crashes here due to forced unwrap of imageName (nil)
if !FileManager.default.fileExists(atPath: localPath!.path) {
do {
try UIImageJPEGRepresentation(image, 1.0)?.write(to: localPath!)
print("file saved")
}catch {
print("error saving file")
}
}
else {
print("file already exists")
}
...
dismiss(animated: true, completion: nil)
}