Hello!
I want to use PhotosPicker
, but I'm encountering an error with the line item.loadTransferable(type: Data.self)
which says Instance method 'loadTransferable(type:)' requires that 'Data' conform to 'Transferable'. I cannot execute the code because of this error. Why is this happening? Any information would be helpful.
I tried changing type: Data.self
to type: UIImage.self
, but it still didn’t work.
I am using Xcode 15.4, and my target version is iOS 17.4.
import SwiftUI
import PhotosUI
struct PhotosPicker: View {
@State var selectedItems: [PhotosPickerItem] = []
@State var selectedImages: [UIImage] = []
var body: some View {
VStack {
if !selectedImages.isEmpty {
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(selectedImages, id: \.self) { image in
Image(uiImage: image)
.resizable()
.scaledToFill()
.frame(width: 300, height: 200)
}
}
}
}
PhotosPicker(
selection: $selectedItems,
selectionBehavior: .ordered,
matching: .images
) {
Text("image!")
}
}
.onChange(of: selectedItems) { items in
Task {
selectedImages = []
for item in items {
guard let data = try await item.loadTransferable(type: Data.self) else { continue }
guard let uiImage = UIImage(data: data) else { continue }
selectedImages.append(uiImage)
}
}
}
}
}
@max_us Bringing Photos picker to your SwiftUI app Sample project covers how you could retrieve a SwiftUI image by using Transferable.