SwiftUI上で必要最低限のコードでカメラのプレビューを表示します。
- フロントカメラのみ
- デバイスの向きはポートレートのみ
- カメラのアクセス許可のチェックなし
環境
- Swift: 5.3.2
- Xcode: 12.4 (12D4e)
- macOS: Big Sur 11.1 (20C69)
コード
ContentView.swift
import SwiftUI
import AVFoundation
struct ContentView: View {
var body: some View {
CameraView()
.edgesIgnoringSafeArea(.all)
}
}
struct CameraView: UIViewRepresentable {
func makeUIView(context: Context) -> UIView { BaseCameraView() }
func updateUIView(_ uiView: UIViewType, context: Context) {}
}
class BaseCameraView: UIView {
override func layoutSubviews() {
super.layoutSubviews()
_ = initCaptureSession
(layer.sublayers?.first as? AVCaptureVideoPreviewLayer)?.frame = frame
}
lazy var initCaptureSession: Void = {
guard let device = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInWideAngleCamera],
mediaType: .video,
position: .unspecified)
.devices.first(where: { $0.position == .front }),
let input = try? AVCaptureDeviceInput(device: device) else { return }
let session = AVCaptureSession()
session.addInput(input)
session.startRunning()
layer.insertSublayer(AVCaptureVideoPreviewLayer(session: session), at: 0)
}()
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Info.plist
<key>NSCameraUsageDescription</key>
<string>This app uses the camera</string>
リポジトリ