Use the SwiftUI PhotosPicker
Written by Team Kodeco
SwiftUI provides a powerful tool for browsing and selecting images and videos from the photo library: the PhotosPicker
view. This component seamlessly blends into your iOS app and offers both single and multiple selection capabilities. This section demonstrates how to leverage PhotosPicker
by creating a photo gallery app. The app will select images from the device’s photo library and present them in a grid layout.
To begin with, import the necessary frameworks: SwiftUI
and PhotosUI
.
import SwiftUI
import PhotosUI
Next, create the ContentView
:
struct ContentView: View {
@State private var selectedItems = [PhotosPickerItem]()
@State private var images = [UUID: Image]()
var body: some View {
ZStack {
ScrollView {
LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))]) {
ForEach(Array(images.keys), id: \.self) { key in
images[key]!
.resizable()
.scaledToFill()
.frame(width: 100, height: 100)
.clipped()
}
}
}
VStack {
Spacer()
PhotosPicker(selection: $selectedItems, matching: .images) {
Text("Select Images")
}
.task(id: selectedItems, {
await loadImages(from: selectedItems)
})
Spacer()
}
}
}
private func loadImages(from items: [PhotosPickerItem]) async {
for item in items {
do {
let image = try await item.loadTransferable(type: Image.self)
if let image = image {
images[UUID()] = image
}
} catch {
print("Failed to load image: \(error)")
}
}
}
}
After you tap Select Images, your preview should look like this:
This example showcases an effective way to create an interactive photo picker using SwiftUI. Key points include:
- A
ZStack
which layers aScrollView
for displaying the images and aPhotosPicker
view for selecting images. - The
LazyVGrid
within theScrollView
presents the selected images in a flexible grid layout. - The
task
modifier, combined with Swift’sasync/await
syntax, provides an elegant solution to load images asynchronously as theselectedItems
changes. - The
loadImages(from:)
function is marked asasync
and uses ado-catch
block to handle potential errors when loading images, making error handling cleaner and more explicit.
With the ability to select images from your photo library and present them directly within your SwiftUI app, this example illustrates a practical real-world application of SwiftUI’s PhotosPicker
.