我正在构建一个自定义相机应用程序,当我按“拍照”按钮时,它会一直显示给我
“没有有效的视频连接”。
我认为这是委派问题,但我不确定要解决的问题。
我在堆栈中尝试了其他解决方案,但没有一个起作用。我是Swift的新手,所以详细的答案将非常有帮助。
@IBOutlet weak var imageView: UIView!
@IBOutlet weak var outputImageView: UIImageView!
@IBAction func takePhotoBtnPressed(_ sender: Any) {
let settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.jpeg])
stillImageOutput!.capturePhoto(with: settings, delegate: self)
}
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let imageData = photo.fileDataRepresentation()
else { return }
let image = UIImage(data: imageData)
outputImageView.image = image
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.session!.stopRunning()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
session = AVCaptureSession()
session.sessionPreset = .low
guard let backCamera = AVCaptureDevice.default(for: AVMediaType.video)
else {
print("Unable to access back camera!")
return
}
do {
let input = try AVCaptureDeviceInput(device: backCamera)
stillImageOutput = AVCapturePhotoOutput()
if session.canAddInput(input) && session.canAddOutput(stillImageOutput) {
session.addInput(input)
session.addOutput(stillImageOutput)
setupLivePreview()
}
}
catch let error {
print("Error Unable to initialize back camera: \(error.localizedDescription)")
}
stillImageOutput = AVCapturePhotoOutput()
}
func setupLivePreview() {
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: session)
videoPreviewLayer.videoGravity = .resizeAspectFill
videoPreviewLayer.connection?.videoOrientation = .portrait
imageView.layer.addSublayer(videoPreviewLayer)
DispatchQueue.global(qos: .userInitiated).async { //[weak self] in
self.session.startRunning()
DispatchQueue.main.async {
self.videoPreviewLayer.frame = self.imageView.bounds
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
if AVCaptureDevice.authorizationStatus(for: .video) == .authorized {
print("yes auth")
} else {
AVCaptureDevice.requestAccess(for: .video, completionHandler: { (granted: Bool) in
if granted {
} else {
print("no auth")
}
})
}
}
}
它的错误消息是:
由于未捕获的异常“ NSGenericException”而终止应用程序,原因:“ ***-[AVCapturePhotoOutput capturePhotoWithSettings:delegate:]没有活动和启用的视频连接”