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


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)


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.


TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out 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.