Created
July 23, 2022 13:37
-
-
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/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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