0

How can I use a picture from the Photo Library in my app? I have done the tutorials about credating a photo app. That all works fine. I have a UIPickerController, can take a picture with the camera, save it to the library, or select an image from the library, which is then put onto the screen. But...

What I want is that the user selects a picture, remember the name of the picture or the number or something, and then on another page use this picture from the library.

Like selecting an avatar. Saving the picture somewhere and whenever the user enters the profile page, open up this avatar picture previously selected. So what I need is the "name"(represenation) of the picture, but I can't find that. How do I do that?

(the code below is just the working cam/lib app part, but it saves the picture without name, that's the problem: How do I find out what picture was saved earlier?) P.S. Sorry, variable names are in Dutch.

class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    @IBOutlet weak var plaatje: UIImageView!

    @IBAction func saveknop(_ sender: UIButton) {
        let imageData = UIImageJPEGRepresentation(plaatje.image!, 0.6)
        let compressedfoto = UIImage(data: imageData!)
        UIImageWriteToSavedPhotosAlbum(compressedfoto!, nil, nil, nil)
        saveNotice()
    }

    @IBAction func cameraknop(_ sender: UIButton) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.camera
            imagePicker.allowsEditing = false
            self.present(imagePicker, animated: true, completion: nil)
        }
    }

    @IBAction func biepknop(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
            imagePicker.allowsEditing = true
            self.present(imagePicker, animated: true, completion: nil)
        }
    }


    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
        plaatje.image = image
        self.dismiss(animated: true, completion: nil)
    }

    func saveNotice() {
        let alert = UIAlertController(title: "foto genomen", message: "je foto is bewaard in de biep", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(defaultAction)
        present(alert, animated: true, completion: nil)

    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • P.S. I realise (thx Jared!) that I will get an error if the picture should be erased by the user, but I expect to build in a solution for that (displaying a question mark or something). That way the user can make a new picture. –  Jan 08 '17 at 19:33
  • Is this the answer? http://stackoverflow.com/questions/27854937/ios8-photos-framework-how-to-get-the-nameor-filename-of-a-phasset –  Jan 08 '17 at 20:25

3 Answers3

0

One solution I found is to use UIImageJPEGRepresentation or UIImagePNGRepresentation to convert the image into a Data object. From there you can use the write(to:) method to save it to the specific URL you want your app to use.

The answer to this SO question shows a few ways to store the image. It might be of help.

Community
  • 1
  • 1
0

I had the same trouble earlier, this did the trick for me:

Save images using the following method:

func saveImage(image: UIImage, path: String ) {
    let pngImageData = UIImagePNGRepresentation(image)

    do {
        try pngImageData?.write(to: URL(fileURLWithPath: path), options: .atomic)
    } catch {
        print(error)
    }
}

Load saved images using:

func loadImageFromName(name: String) -> UIImage? {

    let path = self.fileInDocumentsDirectory(filename: name)

    let image = UIImage(contentsOfFile: path)

    if image == nil {
        print("Image not available at: \(path)")
    }

    return image
}

func fileInDocumentsDirectory(filename: String) -> String {
    let documentsFolderPath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] as NSString
    return documentsFolderPath.appendingPathComponent(filename)
}

Call the save method like this:

saveImage(image: image, path: fileInDocumentsDirectory(filename: "someId"))

Good luck! Hope this helps.

rodrigochousal
  • 401
  • 4
  • 19
0

Struggeling with the suggestions, I found another solution, that is strangely simple. But it works! Weird. It is not the best one, but for now I'll use this, untill I understand everyuthiong about the directorys and filesystem on the iphone.

P.S. credit goes to: http://theswiftguy.com/index.php/2016/11/10/how-to-save-an-image-locally-in-xcode-8-swift-3-0/

        //Encoding
    let image = UIImage(named: "dog.png")
    let imageData:NSData = UIImagePNGRepresentation(image!)! as NSData

    //Saved image
    UserDefaults.standard.set(imageData, forKey: "savedImage")

    //Decode
    let data = UserDefaults.standard.object(forKey: "savedImage") as! NSData
    myImageView.image = UIImage(data: data as Data)