文章目录
- 官方文档
- 示例代码:
- AVCaptureDevice.default方法三个参数的解释
官方文档
苹果官方文档:Setting Up a Capture Session
示例代码:
import UIKit
import AVFoundationclass PreviewView: UIView {
override class var layerClass: AnyClass {
return AVCaptureVideoPreviewLayer.self}var videoPreviewLayer: AVCaptureVideoPreviewLayer {
return layer as! AVCaptureVideoPreviewLayer}}class ViewController: UIViewController {
var captureSession: AVCaptureSession?let previewView = PreviewView()override func viewDidLoad() {
super.viewDidLoad()// Do any additional setup after loading the view.switch AVCaptureDevice.authorizationStatus(for: .video) {
case .authorized: // The user has previously granted access to the camera.self.setupCaptureSession()case .notDetermined: // The user has not yet been asked for camera access.AVCaptureDevice.requestAccess(for: .video) {
granted inif granted {
self.setupCaptureSession()}}case .denied: // The user has previously denied access.returncase .restricted: // The user can't grant access due to restrictions.return}}func setupCaptureSession() {
captureSession = AVCaptureSession()guard let captureSession = captureSession else {
return}captureSession.beginConfiguration()let videoDevice = AVCaptureDevice.default(.builtInWideAngleCamera, for: .video, position: .back)guard let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice!),captureSession.canAddInput(videoDeviceInput) else {
return}captureSession.addInput(videoDeviceInput)let photoOutput = AVCapturePhotoOutput()guard captureSession.canAddOutput(photoOutput) else {
return }captureSession.sessionPreset = .photocaptureSession.addOutput(photoOutput)captureSession.commitConfiguration()previewView.frame = view.boundspreviewView.videoPreviewLayer.session = captureSessionview.addSubview(previewView)captureSession.startRunning()}}
AVCaptureDevice.default方法三个参数的解释
参数的枚举选择不对,可能会导致初始化失败。如设备类型你选了.builtInDualWideCamera.但是6s的手机没有两个广角相机,那么在6s手机上运行是就会返回nil
设备类型 AVCaptureDevice.DeviceType
参考:
OC之AVCaptureDevice