How to retrieve the file path (URL) of the most recent photo from the gallery?

时间:2018-07-25 04:52:22

标签: ios swift photolibrary

I'm working with the Image Picker and when I try to retrieve the file path from a selected photo of the gallery then everything works fine.
However when I try to do the same with the camera option the file path always returns nil.

After searching the web I came across this answer which helped me understand the problem, I should save the photo and then try to access it's file path, and that's exactly my problem here.

After searching the web again I found similar questions like this one and this one, however none of them have an updated way of retrieving the file path of a newly taken photo from the gallery, every piece of code I tried ended up with issues or where in obj-c.

My code looks like this:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {

    self.addPhotoButton.titleLabel?.layer.opacity = 0

    denouncementPhoto = info[UIImagePickerControllerOriginalImage] as? UIImage
    denouncementPhotoImageView.image = denouncementPhoto

    if self.imagePicker.sourceType == UIImagePickerControllerSourceType.camera {
        UIImageWriteToSavedPhotosAlbum(denouncementPhoto!, self, #selector(image(image:didFinishSavingWithError:contextInfo:)), nil)
    } else {
        if #available(iOS 11.0, *) {
            imageURL = info[UIImagePickerControllerImageURL] as? URL
        } else {
            // Fallback on earlier versions
        }
        print("imageURL: ", imageURL)
    }

    imagePicker.dismiss(animated: true, completion: nil)
}

@objc private func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: UnsafeMutableRawPointer?) {
    if ((error) != nil) {
        // Do anything needed to handle the error or display it to the user
    } else {

    }
}

0 个答案:

没有答案