TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Project 10/ Day 43: Importing photos with UIImagePickerController

Forums > 100 Days of Swift

@Sammy  

I am having difficulty with the code below. When the jpegData for image is written to imagePath, does imagePath generate a random uuidString for the jpegData because we appended imageName as a path component?

I am having difficulty understanding this portion of the code:

let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    guard let image = info[.editedImage] as? UIImage else { return }

    let imageName = UUID().uuidString
    let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

    if let jpegData = image.jpegData(compressionQuality: 0.8) {
        try? jpegData.write(to: imagePath)
    }

    dismiss(animated: true)
}

3      

In this project we are choosing a photo from the photo library, editing it, and then saving it in a file that our app can access later.

Since we are just pulling the image from the photo library, we don't really have any name to reference it by. So, we are just creating a random ID number for it, and using that for a name.

Using a UUID just makes it easy for us to create individual names for each photo, and ensure that they will all be unique, without having to create them ourselves.

The line of code you mentioned...

let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

is basically just finding the Documents directory for us, and creating a file in it with the file name matching the random ID number that we generated to use as the name for that photo.

Then we write the jpeg image data to the file that was created.

4      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.