History
Loading...
Loading...
September 12, 2025
PhotosPicker instead of deprecated image picker APIs. It provides system-native UI with automatic privacy handling and supports multiple selection modes. Simply import PhotosUI and use PhotosPicker(selection: $selectedItems, matching: .images) for instant photo access.This approach uses async/await to load selected images properly, handles the data conversion safely with optional binding, and maintains clean state management between picker selection and image display.
import SwiftUI
import PhotosUI
struct PhotoPickerView: View {
@State private var selectedItem: PhotosPickerItem?
@State private var selectedImage: Image?
var body: some View {
VStack {
PhotosPicker("Select Photo",
selection: $selectedItem,
matching: .images)
if let selectedImage {
selectedImage
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxHeight: 300)
}
}
.onChange(of: selectedItem) { _, newItem in
Task {
if let data = try? await newItem?.loadTransferable(type: Data.self) {
if let uiImage = UIImage(data: data) {
selectedImage = Image(uiImage: uiImage)
}
}
}
}
}
}PhotosPicker requires asynchronous data loading since images can be large or stored in iCloud. Using Task with proper error handling prevents UI blocking and crashes while providing a responsive user experience. The onChange modifier ensures the image loads immediately when selected.