2016-10-22 4 views
0

Входной сигнал был определен как try AVCaptureDeviceInput(device: captureDevice), но он по-прежнему говорит, что input является нерешенным идентификатором. См. Мой код ниже, я пробовал несколько методов, но не успел.использование неразрешенного идентификатора

import UIKit 
import AVFoundation 

class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate { 

    var captureSession: AVCaptureSession? 
    var videoPreviewLayer: AVCaptureVideoPreviewLayer? 
    var qrCodeFrameView: UIView? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     // Get an instance of AVCaptureDevice class to initialize a device object and provide the video as the media type parameter. 

     let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 

     // Get an instance of the AVCaptureDeviceInput class using the previous device object. 
     do { 
      let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
      let input = try AVCaptureDeviceInput(device: captureDevice) 
      // Do the rest of your work... 
     } catch let error as NSError { 
      // Handle any errors 
      print(error) 
     } 

     // Initialize the captureSession object 
     captureSession = AVCaptureSession() 
     captureSession?.addInput(input as! AVCaptureInput) 

     // Set the input device on the capture session. 


     // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session. 
     let captureMetadataOuput = AVCaptureMetadataOutput() 
     captureSession?.addOutput(captureMetadataOuput) 

     // Set delegate and use the default dispatch queue to execute the call back 
     captureMetadataOuput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) 
     captureMetadataOuput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] 

     // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer. 
     videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill 
     videoPreviewLayer?.frame = view.layer.bounds 
     view.layer.addSublayer(videoPreviewLayer!) 

     // Start video capture 
     captureSession?.startRunning() 



    } 

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

Как исправить это?

+0

Это потому, что 'input' не определено, что это сфера. Вам нужно положить остальную часть cade с помощью 'captureSession' и т. Д., Где вы написали' // Делаем остальную часть вашей работы ... 'после' let input' – Larme

ответ

0

Это проблема с объемом. Ваши константы captureDevice и input могут использоваться только внутри блока do. Обновите код на что-то вроде этого:

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Get an instance of AVCaptureDevice class to initialize a device object and provide the video as the media type parameter. 

    let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 

    // Get an instance of the AVCaptureDeviceInput class using the previous device object. 
    do { 
     let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
     let input = try AVCaptureDeviceInput(device: captureDevice) 

     // Initialize the captureSession object 
     captureSession = AVCaptureSession() 
     captureSession?.addInput(input as! AVCaptureInput) 

     // Set the input device on the capture session. 


     // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session. 
     let captureMetadataOuput = AVCaptureMetadataOutput() 
     captureSession?.addOutput(captureMetadataOuput) 

     // Set delegate and use the default dispatch queue to execute the call back 
     captureMetadataOuput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) 
     captureMetadataOuput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] 

     // Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer. 
     videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill 
     videoPreviewLayer?.frame = view.layer.bounds 
     view.layer.addSublayer(videoPreviewLayer!) 

     // Start video capture 
     captureSession?.startRunning() 
    } catch let error as NSError { 
     // Handle any errors 
     print(error) 
    } 
} 
0

input в рамках do блока, он не виден снаружи.

В принципе, это очень плохая идея, чтобы просто напечатать ошибку и продолжить, как будто ничего не произошло. Всегда кладите весьхороший код в do блока:

do { 
    let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
    let input = try AVCaptureDeviceInput(device: captureDevice) 
    // Initialize the captureSession object 
    captureSession = AVCaptureSession() 
    captureSession?.addInput(input as! AVCaptureInput) 

    // Initialize a AVCaptureMetadataOutput object and set it as the output 

... 

    // Start video capture 
    captureSession?.startRunning() 

    // Do the rest of your work... 
} catch let error as NSError { 
    // Handle any errors 
    print(error) 
} 
+0

спасибо, что это сработало –

1

Как уже говорилось в других ответах, ваш input переменная ограничена объема do блока.

Альтернативное решение - если вы хотите сохранить делать/уловах блоки меньше и локализованы - это объявить переменную вне блока:

let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
    let input: AVCaptureDeviceInput 
    do { 
     input = try AVCaptureDeviceInput(device: captureDevice) 
    } catch let error as NSError { 
     print(error) 
     return // Must return from method here ... 
    } 

    // `input` is defined and initialized now ... 
    captureSession = AVCaptureSession() 
    captureSession?.addInput(input) 
    // ... 

Обратите внимание, что это требует, чтобы ваше возвращение сразу в ошибка кейс, как input будет не определено тогда.

Или, если сообщение об ошибке не важно, использовать try? в guard заявление:

let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) 
    guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { 
     return 
    } 

    // `input` is defined and initialized now ... 
    captureSession = AVCaptureSession() 
    captureSession?.addInput(input) 
    // ... 
Смежные вопросы