首页 文章

我的自定义相机视图有什么问题?

提问于
浏览
0

我按照这个视频:https://www.youtube.com/watch?v=7TqXrMnfJy8&t=45s到T.但是当我打开相机视图时,我看到的只有黑屏和白色按钮 . 当我尝试加载摄像机视图时,我没有收到任何错误消息 . 有人可以帮我解决我做错的事吗?

我的代码如下:

import UIKit
import AVFoundation

class CameraViewController: UIViewController {

var captureSession = AVCaptureSession()
var backCamera: AVCaptureDevice?
var currentCamera: AVCaptureDevice?

var photoOutput: AVCapturePhotoOutput?

var cameraPreviewLayer: AVCaptureVideoPreviewLayer?

override func viewDidLoad() {
    super.viewDidLoad()

    setupCaptureSession()
    setupDevice()
    setupInputOutput()
    setupPreviewLayer()
    startRunningCaptureSession()

}

func setupCaptureSession(){
    captureSession.sessionPreset = AVCaptureSession.Preset.photo
}
func setupDevice(){
    let deviceDiscoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [AVCaptureDevice.DeviceType.builtInWideAngleCamera], mediaType: AVMediaType.video, position: AVCaptureDevice.Position.unspecified)
    let devices = deviceDiscoverySession.devices

    for device in devices{
        if device.position == AVCaptureDevice.Position.back {
            backCamera = device
        }
    }

    currentCamera = backCamera
}

func setupInputOutput(){

    do {
        let captureDeviceInput = try AVCaptureDeviceInput(device: currentCamera!)
        captureSession.addInput(captureDeviceInput)
        photoOutput?.setPreparedPhotoSettingsArray([AVCapturePhotoSettings(format:[AVVideoCodecKey: AVVideoCodecType.jpeg])], completionHandler: nil)
    } catch {
        print(error)
    }

}

func setupPreviewLayer(){
    cameraPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
    cameraPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
    cameraPreviewLayer?.connection?.videoOrientation = AVCaptureVideoOrientation.portrait
    cameraPreviewLayer?.frame = self.view.frame
    self.view.layer.insertSublayer(cameraPreviewLayer!, at: 1)
}

func startRunningCaptureSession(){
    captureSession.startRunning()
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated
}
}

1 回答

  • 1

    我运行你的代码,它工作得很好 - 几乎!唯一的问题是我必须在应用程序的Info.plist中添加一个Privacy-Camera Usage Description条目 . 否则应用程序崩溃 .

    一旦我这样做并运行了你的代码,我就在设备上看到了实时摄像头视图 .

    那为什么不适合你呢?让我们想一些可能的原因 . 您没有提供足够的信息以确定(看到代码本身工作正常),但这里有一些可能性:

    • 你没有't have the Privacy — Camera Usage Description entry in the app'的Info.plist .

    • 您正在模拟器上进行测试 . 也许此代码仅适用于设备 .

    • 当您说 insertSublayer 时,您在子界面前面添加了一些内容 . 要测试这个,请尝试说 addSublayer ;这将使相机层成为最前层(这仅用于测试目的,请记住) .

    • 也许你的代码根本不会运行?也许我们从未真正去过这个视图控制器 . 要测试该理论,请在 viewDidLoad 中放置 print 语句,并查看它是否实际打印到控制台 .

    • 也许您的代码运行得太快了?为了测试这个理论,将所有这些调用移出 viewDidLoad 并稍后进入某些东西,例如 viewDidAppear . 请记住,这仅用于测试目的 .

    希望其中一个可以帮助您找出问题所在 .

相关问题