Chetan
Chetan

Reputation: 226

How to get image name from UIImagePickerController taken with Camera

This below code is working perfectly fine for images picked from gallery. But will not work if taken with Camera. I tried to save image into storage and read again, but I was unable to do that. So could any one help me in this? Thank you.

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


    if let referenceUrl = info[UIImagePickerControllerReferenceURL] as? NSURL, image = info[UIImagePickerControllerOriginalImage] as? UIImage  {
            let phAsset = PHAsset.fetchAssetsWithALAssetURLs([referenceUrl], options: nil).lastObject as! PHAsset
            PHImageManager.defaultManager().requestImageDataForAsset(phAsset, options: PHImageRequestOptions(), resultHandler: { (imagedata, dataUTI, orientation, info) in
                if info!.keys.contains(NSString(string: "PHImageFileURLKey")) {
                    let path = info![NSString(string: "PHImageFileURLKey")] as! NSURL
                    print("path q\(path)")

                    self.mImageUrl = path
                    self.mlocalPath = path.path
                    self.mImageExtension = path.pathExtension
                    self.mImageName = path.lastPathComponent!
                    print("mImageName q\(self.mImageName)")
                }

            })
    }

    dismissViewControllerAnimated(true, completion: nil)

}

Upvotes: 1

Views: 3570

Answers (3)

Keshu R.
Keshu R.

Reputation: 5225

Swift 5+

As the previous answers sugested, the image is not stored in gallery yet and hence no imageName. You need to store it in gallery. Use the below Helper class to save and get images from FileManager.

Thanks to this Answer

class CameraImageManager {
    
    static let shared = CameraImageManager()

   public func saveImage(imageName: String, image: UIImage) {

        guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

        let fileName = imageName
        let fileURL = documentsDirectory.appendingPathComponent(fileName)
        guard let data = image.jpegData(compressionQuality: 1) else { return }

        //Checks if file exists, removes it if so.
        if FileManager.default.fileExists(atPath: fileURL.path) {
            do {
                try FileManager.default.removeItem(atPath: fileURL.path)
                print("Removed old image")
            } catch let removeError {
                print("couldn't remove file at path", removeError)
            }

        }

        do {
            try data.write(to: fileURL)
        } catch let error {
            print("error saving file with error", error)
        }

    }

    public func getImagePathFromDiskWith(fileName: String) -> URL? {

        let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

        let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

        if let dirPath = paths.first {
            let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
            return imageUrl
        }

        return nil
    }

   public func loadImageFromDiskWith(fileName: String) -> UIImage? {

        let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

        let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
        let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

        if let dirPath = paths.first {
            let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
            let image = UIImage(contentsOfFile: imageUrl.path)
            return image

        }

        return nil
    }

}

Now, in your imagePickerController didFinishPickingMediaWithInfo callback function, this is how you can assign a name to an image and save it.

public func imagePickerController(_ picker: UIImagePickerController,
                                  didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }
    let imageName = "RDV_" + UUID().uuidString
    CameraImageManager.shared.saveImage(imageName: imageName, image: image)
    print("IMAGE NAME IS: ", imageName)
}

Hope It Helps.

Upvotes: 3

user7014451
user7014451

Reputation:

The image isn't in the gallery yet, so I don't believe you have a name.

In my app the flow (via navigation controller) is:

  • Selection VC (choice of Camera or Photo Library) ->
  • UIImagePickerController ->
  • Edit VC (with back navigation and action button for - among others - saving to Photo Library)

If the user chooses Camera, they take a picture and the options are "Retake" or "Use Photo". Is they choose "Use Photo", they are in the Edit VC.

If they then choose to go back to the Select VC, the image is nowhere to be found.

Upvotes: 0

niravdesai21
niravdesai21

Reputation: 4838

You can use a notification with addObserver like this

ViewController A : where you want image to be changed, add this in viewDidLoad

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.methodOfImageChange(_:)), name:"ImageChanged", object: nil)

Add this method in ViewController A

func methodOfImageChange(notification: NSNotification){
    let appStatus = notification.userInfo as? Dictionary<String,AnyObject>   
    // appStatus contains your image in "image" key 
   }

Now in didFinishPickingMediaWithInfo add this

let dictionary: [String:AnyObject] = [
        "image" : (info[UIImagePickerControllerOriginalImage] as? UIImage)!,
        ]
    NSNotificationCenter.defaultCenter().postNotificationName("ImageChanged", object: self, userInfo: dictionary)

    picker .dismissViewControllerAnimated(true, completion: nil)

Hope this helps

Upvotes: 0

Related Questions