Design Converter
Education
Software Development Executive - III
Last updated on Jan 20, 2025
Last updated on Dec 27, 2024
If you’re developing a SwiftUI app and need to access and manage the photo library, the SwiftUI Image Picker is a highly useful tool. It allows users to select and interact with photos in an intuitive manner.
In this blog, we’ll dive deep into how you can implement and customize a photos picker, optimize memory usage, and manage data effectively. From setting up the picker to handling selected images, we’ll cover it all with practical examples.
The SwiftUI Image Picker simplifies the task of accessing the photo library by providing a user-friendly interface for selecting images. Whether you need to select multiple photos or focus on a single image, the image picker streamlines the entire process. This functionality is particularly useful when your app involves displaying user-selected content, uploading photos, or creating customized galleries.
To get started, you need to import the required frameworks. Use the following code to bring in SwiftUI and PhotosUI, which powers the photos picker functionality.
1import SwiftUI 2import PhotosUI
The PhotosUI framework provides tools to create customizable pickers for interacting with the photos library.
You’ll typically define your user interface within a struct ContentView. Here’s how to set up the picker in the body property of a SwiftUI view, allowing users to select images.
1struct ContentView: View { 2 // State variables to manage the selected image and picker presentation state 3 @State private var selectedImage: UIImage? = nil 4 @State private var isPickerPresented: Bool = false 5 6 var body: some View { 7 VStack { 8 if let selectedImage = selectedImage { 9 Image(uiImage: selectedImage) 10 .resizable() 11 .frame(width: 200, height: 200) 12 } else { 13 Text("No Image Selected") 14 .font(.headline) 15 } 16 17 Button("Select Photo") { 18 isPickerPresented = true 19 } 20 .sheet(isPresented: $isPickerPresented) { 21 PhotoPicker(selectedImage: $selectedImage) 22 } 23 } 24 } 25}
In this example, the picker is wrapped in a sheet for smooth user interaction.
The PhotoPicker component, a custom implementation of UIViewControllerRepresentable, connects the photos picker to your app, enabling you to load and handle user-selected images.
1struct PhotoPicker: UIViewControllerRepresentable { 2 @Binding var selectedImage: UIImage? 3 4 func makeUIViewController(context: Context) -> PHPickerViewController { 5 var config = PHPickerConfiguration(photoLibrary: .shared()) 6 config.selectionLimit = 1 7 config.filter = .images 8 9 let picker = PHPickerViewController(configuration: config) 10 picker.delegate = context.coordinator 11 return picker 12 } 13 14 func updateUIViewController(_ uiViewController: PHPickerViewController, context: Context) {} 15 16 func makeCoordinator() -> Coordinator { 17 Coordinator(self) 18 } 19 20 // Coordinator to handle picker delegate methods 21 class Coordinator: NSObject, PHPickerViewControllerDelegate { 22 let parent: PhotoPicker 23 24 init(_ parent: PhotoPicker) { 25 self.parent = parent 26 } 27 28 func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) { 29 picker.dismiss(animated: true) 30 31 guard let provider = results.first?.itemProvider, provider.canLoadObject(ofClass: UIImage.self) else { return } 32 33 provider.loadObject(ofClass: UIImage.self) { (image, error) in 34 DispatchQueue.main.async { 35 if let uiImage = image as? UIImage { 36 self.parent.selectedImage = uiImage 37 } 38 } 39 } 40 } 41 } 42}
Here’s a breakdown of the matching parameters used in the picker configuration:
selectionLimit
determines if you want to select multiple photos or just one.filter = .images
ensures that only images appear in the picker.Once the user selects an image, it’s important to manage memory usage effectively. Large images can consume significant resources, so resize or compress them before processing.
1extension UIImage { 2 // Resize images to optimize memory usage and improve app performance 3 func resize(to targetSize: CGSize) -> UIImage? { 4 UIGraphicsBeginImageContext(targetSize) 5 draw(in: CGRect(origin: .zero, size: targetSize)) 6 let resizedImage = UIGraphicsGetImageFromCurrentImageContext() 7 UIGraphicsEndImageContext() 8 return resizedImage 9 } 10}
Resizing assets reduces the strain on your app’s storage and improves performance during display.
If you want to select multiple photos, modify the picker configuration. Use an array to hold the selected images.
1@State private var selectedImages: [UIImage] = [] 2 3var body: some View { 4 PhotosPicker(selection: $selectedImages) { 5 Text("Select Multiple Photos") 6 } 7}
To display the selected images in a gallery, consider adding a ScrollView
or LazyVGrid
.
1ScrollView { 2 LazyVGrid(columns: [GridItem(.adaptive(minimum: 100))]) { 3 ForEach(selectedImages, id: \ .self) { image in 4 Image(uiImage: image) 5 .resizable() 6 .frame(width: 100, height: 100) 7 } 8 } 9}
.frame
modifiers to keep your UI consistent across screen sizes.print
statements to verify picker configuration and image selection during development.The SwiftUI Image Picker is a powerful and flexible tool that enhances the user experience by integrating with the photo library. Whether you need to select multiple photos, optimize memory usage, or manage data efficiently, the photos selector makes it easy to handle user-selected content. By leveraging the features discussed in this guide, you can create robust, user-friendly apps with seamless image management.
Try implementing the SwiftUI Image Picker today and take your app’s functionality to the next level!
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.