Skip to content

Instantly share code, notes, and snippets.

@StewartLynch
Last active March 17, 2024 22:33
Show Gist options
  • Save StewartLynch/45304cd2cb640f7c334e392e059e2a57 to your computer and use it in GitHub Desktop.
Save StewartLynch/45304cd2cb640f7c334e392e059e2a57 to your computer and use it in GitHub Desktop.
A gist for the YouTube tutorial on picking and adding photos from your photos library
//
// Created for SwiftData-Camera-Photo
// by Stewart Lynch on 2024-03-17
//
// Follow me on Mastodon: @[email protected]
// Follow me on Threads: @StewartLynch (https://www.threads.net)
// Follow me on X: https://x.com/StewartLynch
// Follow me on LinkedIn: https://linkedin.com/in/StewartLynch
// Subscribe on YouTube: https://youTube.com/@StewartLynch
// Buy me a ko-fi: https://ko-fi.com/StewartLynch
import SwiftUI
import PhotosUI
@Observable
class ImagePicker {
var image: Image?
var images: [Image] = []
// Change the UpdateEditFormViewModel to match the name of your own ViewModel
var vm: UpdateEditFormViewModel?
func setup(_ vm: UpdateEditFormViewModel) {
self.vm = vm
}
var imageSelection: PhotosPickerItem? {
didSet {
if let imageSelection {
Task {
try await loadTransferable(from: imageSelection)
}
}
}
}
@MainActor
func loadTransferable(from imageSelection: PhotosPickerItem?) async throws {
do {
if let data = try await imageSelection?.loadTransferable(type: Data.self) {
vm?.data = data
if let uiImage = UIImage(data: data) {
self.image = Image(uiImage: uiImage)
}
}
} catch {
print(error.localizedDescription)
image = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment