I’m trying to find a way to reference photos in the User Photos Library and add those references in a SwiftData record. I can, of course, get the photos from the library, convert to Data type and store that in SwiftData, but I’m trying to avoid duplicating all that data (there will be a lot of photos). I thought I should be able to get a URL for a Photos item, but have not found any way to do that. I tried making a property in the SwiftData model for [PhotosPickerItem] but that fails with the error: “Referencing instance method ‘setValue(forKey:to:)’ on ‘Array’ requires that ‘PhotosPickerItem’ conform to ‘PersistentModel'” in the model initializer.
The idea of the model:
@Model
final public class Thing {
var name: String = ""
var comment: String = ""
var photoPickerItems: [PhotosPickerItem] = []
init(name: String, comment: String) {
self.name = name
self.comment = comment
}
}//class
And then in the picker view:
struct ImagePickerView: View {
@Binding var selectedImageURLs: [URL]
@State private var selectedItems: [PhotosPickerItem] = []
var thing: Thing
var body: some View {
PhotosPicker(selection: $selectedItems, maxSelectionCount: 5, matching: .images, photoLibrary: .shared()) {
Text("Select Images")
.font(.headline)
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.onChange(of: selectedItems) { oldItems, newItems in
Task {
thing.photoPickerItems = []
for item in newItems {
thing.photoPickerItems.append(item)
}
}
}
}
}
I would appreciate any guidance on a way to accomplish the idea. Xcode 15.4, iOS 17.5