Photo Picker in SwiftUI
SwiftUI has evolved significantly, but it still lacks a native photo picker. To fill this gap, we can use PHPickerViewController from UIKit.
With the help of UIViewControllerRepresentable, we can integrate this UIKit controller into SwiftUI seamlessly.
Here’s how you can build a simple and efficient photo picker for your app.
Step 1: Create the PhotoPicker using UIViewControllerRepresentable
The UIViewControllerRepresentable
protocol acts as a bridge, allowing us to embed a UIKit view controller into a SwiftUI view.
Here’s how to build a SwiftUI-compatible photo picker:
Step 2: Display the Photo Picker in a SwiftUI View
Now, integrate the PhotoPicker into a SwiftUI view. Add a button to trigger the photo picker and display the selected image.
Step 3: Test Your Implementation
- Run your app on a real device or a simulator.
- Tap the “Select Image” button to open the Photo Picker.
- Select an image, which will be displayed in your SwiftUI view.