BLACK FRIDAY: Save 50% on all my Swift books and bundles! >>

Importing an image into SwiftUI using PhotosPicker

Paul Hudson    @twostraws   

In order to bring this project to life, we need to let the user select a photo from their library, then display it in ContentView. This takes a little thinking, mostly because of the roundabout way Core Image works compared to SwiftUI.

First we need to add an import for PhotosUI to the top of ContentView, then give it an extra @State property to track whatever picture the user selected:

@State private var selectedItem: PhotosPickerItem?

Second, we need to place a PhotosPicker view wherever we want to trigger an image selection. In this app, we can actually place one around the whole if let processedImage check – we can use the selected image or the ContentUnavailableView as the label for our PhotosPicker.

Here's how that looks:

PhotosPicker(selection: $selectedItem) {
    if let processedImage {
        processedImage
            .resizable()
            .scaledToFit()
    } else {
        ContentUnavailableView("No Picture", systemImage: "photo.badge.plus", description: Text("Import a photo to get started"))
    }
}

Tip: That adds blue coloring to the ContentUnavailableView to signal that's interactive, but you can disable that by adding .buttonStyle(.plain) to the PhotosPicker if you prefer.

Third, we need a method that will be called when the an image has been selected.

Previously I showed you how how we can load data from a PhotosPicker selection, and separately I also showed you how to feed a UIImage into Core Image for filtering. Here we need to kind of bolt those two things together: we can't load a simple SwiftUI image because they can't be fed into Core Image, so instead we load a pure Data object and convert that to a UIImage.

Add this method to ContentView now:

func loadImage() {
    Task {
        guard let imageData = try await selectedItem?.loadTransferable(type: Data.self) else { return }
        guard let inputImage = UIImage(data: imageData) else { return }

        // more code to come
    }
}

We can then call that whenever our selectedItem property changes, by attaching an onChange() modifier somewhere in ContentView – it really doesn’t matter where, but attaching it to the PhotosPicker would seem sensible.

.onChange(of: selectedItem, loadImage)

Go ahead and run the app again – although it won't actually do much with your selection, you can at least bring up the photo selection UI and browse through the options.

Save 50% in my WWDC sale.

SAVE 50% All our books and bundles are half price for Black Friday, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.7/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.