Skip to content

Instantly share code, notes, and snippets.

@LeeKahSeng
Created July 23, 2022 13:37
Show Gist options
  • Save LeeKahSeng/0da5abf8fe7f4063d14ab1b9f35d93f3 to your computer and use it in GitHub Desktop.
Save LeeKahSeng/0da5abf8fe7f4063d14ab1b9f35d93f3 to your computer and use it in GitHub Desktop.
Full sample code for "How to Use the SwiftUI PhotosPicker" (https://swiftsenpai.com/development/swiftui-photos-picker/)
import SwiftUI
import PhotosUI
struct ContentView: View {
@State private var selectedItem: PhotosPickerItem? = nil
@State private var selectedImageData: Data? = nil
var body: some View {
PhotosPicker(
selection: $selectedItem,
matching: .images,
photoLibrary: .shared()) {
Text("Select a photo")
}
.onChange(of: selectedItem) { newItem in
Task {
// Retrieve selected asset in the form of Data
if let data = try? await newItem?.loadTransferable(type: Data.self) {
selectedImageData = data
}
}
}
if let selectedImageData,
let uiImage = UIImage(data: selectedImageData) {
Image(uiImage: uiImage)
.resizable()
.scaledToFit()
.frame(width: 250, height: 250)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment