UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.