gpt4 book ai didi

ios - init() 在 Swift 4 的 AVCaptureDeviceInput 中不可用

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:11:26 25 4
gpt4 key购买 nike

我的应用程序中有一个像 Snapchat 一样显示后置摄像头的 View Controller ,它在 Swift 3 中运行良好,但是当我更新到 Swift 4 时,编译器不允许我运行它,因为出现以下错误:

init() is unavailable for AVCaptureDeviceInput

这个 View Controller 应该像 Snapchat 一样显示没有任何按钮或额外东西的相机。所以,这里是完整的 View Controller 代码:

import UIKit
import AVFoundation

class cameraViewController: UIViewController , UIImagePickerControllerDelegate , UINavigationControllerDelegate {

var captureSession : AVCaptureSession?

var stillImageOutput : AVCaptureStillImageOutput?

var previewLayer : AVCaptureVideoPreviewLayer?

var imagePicker: UIImagePickerController!

@IBOutlet weak var cameraView: UIView!

override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

previewLayer?.frame = cameraView.bounds
}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)


captureSession = AVCaptureSession()

captureSession?.sessionPreset = AVCaptureSessionPreset1280x720

let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

let error : NSError?

var input = AVCaptureDeviceInput()

do {
input = try AVCaptureDeviceInput(device: backCamera)
}
catch {
// error
}

if error == nil && (captureSession?.canAddInput(input))! {

captureSession?.addInput(input)

stillImageOutput = AVCaptureStillImageOutput()

stillImageOutput?.outputSettings = [AVVideoCodecKey : AVVideoCodecJPEG]


if (captureSession?.canAddOutput(stillImageOutput))! {

captureSession?.addOutput(stillImageOutput)

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)

previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill

previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait

cameraView.layer.addSublayer(previewLayer!)

captureSession?.startRunning()

}
}

}

}

由于这一行,我无法运行该应用程序:

var input = AVCaptureDeviceInput()

最佳答案

在 Swift 4 中,您必须指定一个设备才能初始化 AVCaptureDeviceInput - 事实上,您已经在初始化它,在抛出的代码之后用一两行错误。

此外,您在之后的 if 语句中隐式解包了一个安全解包的 AVCaptureSession

这是你的代码,经过优化:

do {
guard let input = try AVCaptureDeviceInput(device: backCamera),
captureSession = captureSession else {
print("Error in initializing a device input")
}

if error == nil && (captureSession.canAddInput(input)) {

[...]
}
catch let error {
print(error.localizedDescription)
}

关于ios - init() 在 Swift 4 的 AVCaptureDeviceInput 中不可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46516278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com