【问题标题】:I can't seem to make a custom camera. "Constant used before initialized"我似乎无法制作自定义相机。 “初始化前使用的常量”
【发布时间】:2016-12-25 12:52:14
【问题描述】:

我正在使用 swift 3。我正在尝试制作自定义相机。但是不管我学了多少教程,或者苹果的文档,总是有错误。

class ViewController: UIViewController, UIImagePickerControllerDelegate {

@IBOutlet var cameraView: UIView!

var captureSession : AVCaptureSession?
var stillImageOutput : AVCaptureStillImageOutput?
var previewLayer : AVCaptureVideoPreviewLayer?

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    captureSession = AVCaptureSession()
    captureSession?.sessionPreset = AVCaptureSessionPreset1920x1080

    let backCamera = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
    let error : NSError?

    do {

        let input = try! AVCaptureDeviceInput (device: backCamera)
        if (error == nil && captureSession?.canAddInput(input) != nil) {

            captureSession?.addInput(input)

            stillImageOutput = AVCaptureStillImageOutput()
            stillImageOutput?.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

            if (captureSession?.canAddOutput(stillImageOutput) != nil) {
                captureSession?.addOutput(stillImageOutput)

                previewLayer = AVCaptureVideoPreviewLayer (session: captureSession)
                previewLayer?.videoGravity = AVLayerVideoGravityResizeAspect
                previewLayer?.connection.videoOrientation = AVCaptureVideoOrientation.portrait
                cameraView.layer.addSublayer(previewLayer!)
                captureSession?.startRunning()
            }
        }
    } catch {

    }
}


override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    previewLayer?.frame = cameraView.bounds
}

在这一行,if (error == nil && captureSession?.canAddInput(input) != nil) {,有一个错误说在初始化之前已经使用了常量“error”。我真的不明白这一点。提前谢谢你。

【问题讨论】:

    标签: swift3 constants avcapturesession


    【解决方案1】:

    正如错误消息所述,您在初始化之前使用了error。您可以通过使用nil 对其进行初始化来解决此问题:

    let error: NSError? = nil
    

    甚至更好:

    let error: Error? = nil
    

    实际上,您从未使用过error,因此您可以简单地将其删除:

    ...
    //let error : NSError? delete this line
    
    do {
        ...
        if (/* error == nil && delete this */captureSession?.canAddInput(input) != nil) {
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-22
      • 2013-03-03
      • 2016-04-13
      • 1970-01-01
      • 2011-10-19
      • 1970-01-01
      相关资源
      最近更新 更多