I am using SwiftUI's PhotosPicker in my application and am trying to find a way to ensure that the next time the user opens PhotosPicker, the number of selected elements is zero.
Simply hare is the code:
PhotosPicker(
selection: $selectedMediaitems,
selectionBehavior: .ordered,
photoLibrary: .shared()
) {
Image(.addIcon)
.resizable()
.frame(width: 60, height: 60)
}
And as I understood I need to set selectedMediaitems = []
somewhere, but I don't understand where and when. If I put this right in function that observes changes on selectedMediaitems I get an infinite function call loop.
Here how I observe changes on selectedMediaitems (this property is inside ViewModel so I made a combine subscription)
$selectedMediaitems
.filter { !$0.isEmpty } // I tried to skip emits that clear array but this way items are still selected in PhotosPicker
.sink(receiveCompletion: {_ in }) { [weak self] items in
self?.saveSelectedMediaFilesFile(items)
self?.deleteFromLibraryItemIds = items.map { $0.itemIdentifier }
//self?.selectedMediaitems = [] // if put it here without .filter { !$0.isEmpty } it will call itself till run time exc.
}
.store(in: &cancellableBag)
You can actually do that immediately after you use those images. I will provide you with a sample project. We first launch the app, we then click on the add button to select photos. We select 1 or more photos. When we do that we can click on display photos, It will display the photos and also make it selectedMediaitems = []. So that when we select photos again, we will not have any pre selected photos.