The PhotosPicker component enables users to import photos or videos from their photos library directly within a SwiftUI app. This reference will guide you through the implementation of this component.
To work with image and video assets managed by the Photos app, we must first import the PhotosUI framework. Next, we create a new variable of PhotosPickerItem type to store the selected image.
After that we can use the PhotosPicker component inside our View.
The PhotosPicker initializer needs a label to describe the action of choosing an item from the photo library and a variable that for the selection parameter. Additionally, we can also specify what type of media we are looking for.
To show the selected image on your interface you need to create a representation of the picked file as a SwiftUI type. You do it by using the loadTransferable(type:) method with the PhotosPickerItem object and using the resulting Image on your SwiftUI interface.
In the example above, when a new image is selected a task is triggered and we load an Image representation of the selected item to be displayed on the interface.