Preselect PhotoPickerItems from Image when reopening PhotosPicker

I'm using the PhotosPicker in my SwiftUI project, like it is provided in the sample code (https://developer.apple.com/documentation/photokit/bringing-photos-picker-to-your-swiftui-app).

Currently it is set up like that: the app loads the images and stores them in CoreData to MyEntity as binary data. However, when a user wants to update the photos there seems to be no possibility to check if the already stored image is already part of the current MyEntity. This means, there seems to be no possibility to preselect already existing images that were selected in a previous session.

Trying to use localIdentifier didn't work either, as it is always nil.

Now I'm wondering, if anyone has an idea on how to solve the given issue, or if there is no option to do so. Any information is appreciated. Thanks!

Answered by kvhd in 820786022

Thanks for your input. profileImage is something you can define yourself. All you get from the PhotoPicker is a Data object and nothing more.

But, I was able to find the issue. Turns out, the localIdentifier was nil as I did not specify a photoLibrary when initializing the PhotosPicker.

So if you initialize your PhotosPicker like that: PhotosPicker(selection: $viewModel.selectedPhotos, matching: .images) the localIdentifier will be nil.

If you set a photoLibrary you will be able to properly retrieve the localIdentifier: PhotosPicker(selection: $selectedPhotos, matching: .images, photoLibrary: .shared())

Found that in the docs page for the localIdentifier itself: https://developer.apple.com/documentation/photosui/photospickeritem/itemidentifier

I haven't run through that sample project myself, but looking at the code is there anything inside profileImage that you can store alongside the image?

So, if profileImage.image is the image data itself, which is what you're storing in MyEntity, is there an identifier in profileImage that you can also store in MyEntity as MyEntity.imageId? Some sort of UUID string? If so, store it, then check for that when you want to pre-select images.

Accepted Answer

Thanks for your input. profileImage is something you can define yourself. All you get from the PhotoPicker is a Data object and nothing more.

But, I was able to find the issue. Turns out, the localIdentifier was nil as I did not specify a photoLibrary when initializing the PhotosPicker.

So if you initialize your PhotosPicker like that: PhotosPicker(selection: $viewModel.selectedPhotos, matching: .images) the localIdentifier will be nil.

If you set a photoLibrary you will be able to properly retrieve the localIdentifier: PhotosPicker(selection: $selectedPhotos, matching: .images, photoLibrary: .shared())

Found that in the docs page for the localIdentifier itself: https://developer.apple.com/documentation/photosui/photospickeritem/itemidentifier

Preselect PhotoPickerItems from Image when reopening PhotosPicker
 
 
Q