Sources/OrgstarMobile/CameraPicker.swift
35 lines · 1294 bytes
7 symbols in this file
1#if os(iOS)
2import SwiftUI
3import UIKit
4
5/// The camera, for a photo to attach; `taken` gets its JPEG data, or nil when cancelled.
6struct CameraPicker: UIViewControllerRepresentable {
7 let taken: (Data?) -> Void
8
9 static var isAvailable: Bool { UIImagePickerController.isSourceTypeAvailable(.camera) }
10
11 func makeUIViewController(context: Context) -> UIImagePickerController {
12 let picker = UIImagePickerController()
13 picker.sourceType = .camera
14 picker.delegate = context.coordinator
15 return picker
16 }
17
18 func updateUIViewController(_ picker: UIImagePickerController, context: Context) {}
19
20 func makeCoordinator() -> Coordinator { Coordinator(taken: taken) }
21
22 final class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
23 let taken: (Data?) -> Void
24 init(taken: @escaping (Data?) -> Void) { self.taken = taken }
25
26 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
27 taken((info[.originalImage] as? UIImage)?.jpegData(compressionQuality: 0.9))
28 }
29
30 func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
31 taken(nil)
32 }
33 }
34}
35#endif