Photos Picker using SwiftUI
In this article, we will check how can we use Photos Picker with SwiftUI. Picker runs out of process hence we don’t need any special library permissions to use it in our apps. If you are supporting iOS 16+ then you can directly use PhotosPicker. Let’s see how can we do it.
import PhotosUI
import SwiftUI
struct PhotoPickerView: View {
@State var wallpaper: PhotosPickerItem?
var body: some View {
PhotosPicker(selection: $wallpaper) {
Label("Select a photo", systemImage: "photo")
}
}
}That’s all we need to do to open the photo picker in SwiftUI. Now we will see how we handle selected images. For this, let’s add an ImageView and set it with the image selected by the user.
var body: some View {
VStack {
Image(systemName: "photo")
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
Spacer()
PhotosPicker(selection: $wallpaper) {
Label("Select a photo", systemImage: "photo")
}
}
}Now, How do we extract images from selected PhotosPickerItem?
For getting image data from PhotosPickerItem we can use the loadTransferable method defined in PhotosPickerItem.
Create one variable to hold the data object representing the picked image and mark it with @State to update UI when the view is changed.
@State private var image: Data?If data is present then use it to create the image and show it else show a placeholder image.
var body: some View {
VStack {
if let image = self.image,
let image = UIImage(data: image) {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
} else {
Image(systemName: "photo")
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
}
Spacer()
PhotosPicker(selection: $wallpaper) {
Label("Select a photo", systemImage: "photo")
}.onChange(of: wallpaper) { oldValue, newValue in
Task {
if let image = try? await newValue?.loadTransferable(type: Data.self) {
self.image = image
}
}
}
}
}Final Code:
import SwiftUI
import PhotosUI
struct ContentView: View {
@State var wallpaper: PhotosPickerItem?
@State private var image: Data?
var body: some View {
VStack {
if let image = self.image,
let image = UIImage(data: image) {
Image(uiImage: image)
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
} else {
Image(systemName: "photo")
.resizable()
.aspectRatio(contentMode: .fit)
.padding()
}
Spacer()
PhotosPicker(selection: $wallpaper) {
Label("Select a photo", systemImage: "photo")
}.onChange(of: wallpaper) { oldValue, newValue in
Task {
if let image = try? await newValue?.loadTransferable(type: Data.self) {
self.image = image
}
}
}
}
}
}That’s it, folks. Hope it helps.
See ya 👋🏻
Related Articles:





