【Xcode/SwiftUI】カメラを起動する

コード

SwiftUIImagePickerというファイルを新規追加

import Foundation
import SwiftUI

struct SwiftUIImagePicker: UIViewControllerRepresentable {
    @Binding var image: UIImage?
    @Binding var showCameraView: Bool
    
    func makeCoordinator() -> Coordinator {
        return Coordinator(self)
    }
    
    func makeUIViewController(context: Context) -> UIImagePickerController {
        let viewController = UIImagePickerController()
        viewController.delegate = context.coordinator
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            viewController.sourceType = .camera
        }
        return viewController
    }
    
    func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) {
        print("updateUIViewController is called")
    }
    
    class Coordinator: NSObject, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
        let parent: SwiftUIImagePicker
        init(_ parent: SwiftUIImagePicker) {
            self.parent = parent
        }
        
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
            // user picked an image
            if let uiImage = info[.originalImage] as? UIImage {
                self.parent.image = uiImage
            }
            self.parent.showCameraView = false
        }
        
        func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            self.parent.showCameraView = false
        }
    }
    
}

ContentViewは以下のように実装

import SwiftUI

struct ContentView: View {
    @State private var image: UIImage?
    @State private var showCameraView = false
    
    var body: some View {
        VStack {
            Text("Take a nice picture!")
                .font(.system(size: 30, weight: .bold))
            if let image = image {
                Image(uiImage: image)
                    .resizable()
                    .frame(width: 400, height: 400)
            } else {
                Image(systemName: "figure.baseball")
                    .resizable()
                    .frame(width: 200, height: 250)
            }
            Button {
                showCameraView.toggle()
            } label: {
                Image(systemName: "camera.circle")
                    .resizable()
                    .scaledToFit()
                    .foregroundColor(.orange)
                    .frame(width: 100, height: 100)
            }
        }
        .fullScreenCover(isPresented: $showCameraView, content: {
            SwiftUIImagePicker(image: self.$image, showCameraView: self.$showCameraView)
        })
    }
}
ひとくちメモ

アプリ内でカメラを使用する場合はInfo.plistに以下の記載が必要です。

Key: Privacy – Camera Usage Description

Value: カメラを使用します (ここのメッセージはカスタマイズ可)