Swift UIで使うためのラッパークラスです。
アルバムから画像を選択するorカメラがあればカメラを起動します。
カメラ起動にはinfo.plistでアクセス権限を許可する必要があります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
// // ImagePickerForSwiftUI.swift // AIImageApp // // Created by nokkun on 2021/10/20. // import Foundation import SwiftUI struct ImagePickerSwiftUI : UIViewControllerRepresentable{ @Binding var image:UIImage? @Binding var showCameraView:Bool func makeCoordinator() -> Coordinator { return Coordinator(self) } func makeUIViewController(context: Context) -> some UIViewController { let viewController = UIImagePickerController() viewController.delegate = context.coordinator if UIImagePickerController.isSourceTypeAvailable(.camera){ viewController.sourceType = .camera } return viewController } func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) { } class Coordinator: NSObject,UIImagePickerControllerDelegate,UINavigationControllerDelegate { let parent: ImagePickerSwiftUI init(_ parent:ImagePickerSwiftUI) { self.parent = parent } //ユーザが写真撮影したり、画像を選択したら、画像を変数に保存する。 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) { if let uiImage = info[.originalImage] as? UIImage { self.parent.image = uiImage } //元の画面に戻る self.parent.showCameraView = false } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { self.parent.showCameraView = false } } } |