5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【SwiftUI】最低限のコードでカメラのプレビューを表示する

Last updated at Posted at 2021-04-16

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>

リポジトリ

5
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
5

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?