【问题标题】:Unresolved Identifier "itemID"未解析的标识符“itemID”
【发布时间】:2016-11-16 22:34:32
【问题描述】:

我如何全局定义(条形码扫描),以便我的所有函数都可以访问它。换句话说,我如何在全局范围内定义“metadataObj”?

class ScanController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

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

override func viewDidLoad() {
super.viewDidLoad()

//Get an instance of the AVCaptureDevice class  a device object and provide the video as the media type parameter
let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)

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

    // Initialize the captureSession object.
     captureSession = AVCaptureSession()

    // Set the input device on the capture session.
    captureSession?.addInput(input)

    let captureMetadataOutput = AVCaptureMetadataOutput()
    captureSession?.addOutput(captureMetadataOutput)

    // Set delegate and use the default dispatch queue to execute the call back
    captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
    captureMetadataOutput.metadataObjectTypes = supportedCodeTypes
    // 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()

    //initialize QR Code Frame to highlight the QR Code

    qrCodeFrameView = UIView()
    if let qrCodeFrameView = qrCodeFrameView {
        qrCodeFrameView.layer.borderColor = UIColor.green.cgColor
        qrCodeFrameView.layer.borderWidth = 2
        view.addSubview(qrCodeFrameView)
    }
} catch {

    // If any error occurs, simply print it out and don't continue any more.
    print(error)
    return
}
}

 func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {

// Check if the metadataObjects array is not nil and it contains at least one object.
if metadataObjects == nil || metadataObjects.count == 0 {
    qrCodeFrameView?.frame = CGRect.zero
    messageLabel.text = "No QR/barcode is detected"
    return
}
//Get metadata object
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject

if supportedCodeTypes.contains(metadataObj.type) {
    //if the found metadata is equal to the QR code metadata then update the status label's text and set the the bounds
    let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
    qrCodeFrameView?.frame = barCodeObject!.bounds

    if metadataObj.stringValue != nil {
        messageLabel.text = metadataObj.stringValue
        //Searches firebase for existing barcode
        }
        let itemToSearchFor = metadataObj.stringValue
        let itemID = metadataObj.stringValue
        guard let Description = productDescriptionTextField.text,
        let price = priceTextField.text,
        let location = productLocationTextField.text
        else{
            print("Fill basic product information")
            return
         }
        let ref = FIRDatabase.database().reference(fromURL: " /")
        // creating an  item child node
        let values = ["Item Description": Description, "Image": price, "Location": location, "Price": price ]

        let items = ref.child("Items").child(itemID!)
        items.updateChildValues(values, withCompletionBlock: { (err, ref) in
            if err != nil {
                print(err)
                return
            } })
         FIRDatabase.database().reference().child("Items").child(itemToSearchFor!).observeSingleEvent(of: .value, with:{(snap) in

                print(snap)

                    })

            self.setupNewProductEntry()
           self.setupenterNewProductButton()
}

            }

当我尝试在另一个函数中使用 ItemID 时出现一个错误。我认为这是因为它不是全局定义的,它仅在 func captureOutput 中定义。关于如何全局定义我从条形码扫描仪获得的条形码字符串值的任何想法?

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    你可以将它移到你的类范围之外,这样它就会变成全局的并且在你的所有模块中都是可见的

    【讨论】:

      【解决方案2】:

      在此处(注释所在的位置)声明它以使其可访问。

      class ScanController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
      
      var captureSession: AVCaptureSession?
      var videoPreviewLayer: AVCaptureVideoPreviewLayer?
      var qrCodeFrameView: UIView?
      //DECLARE itemID here
      override func viewDidLoad() {
      super.viewDidLoad()
      
      //Get an instance of the AVCaptureDevice class  a device object and provide the video as the media type parameter
      let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
      

      【讨论】:

      • 谢谢亚历克,我知道我必须定义它。我的问题实际上是编码。我尝试了很多方法。我必须尝试将其定义为 let itemID = AVCaptureMetadataOutput.string 和许多其他方式,但它没有用。 @vlad
      【解决方案3】:

      只需将“metadataObj”放在全局范围内的类之外(导入部分之后的文件开头,我的意思是,在类声明之外),这样它就不再是类的成员了(并初始化它具有您选择的值)。如果您在框架中声明它并希望在您的应用中使用它,请添加 public 访问修饰符,否则您将无法访问它。 如果您想将它放在类的范围内,但可以从代码中的任何位置访问,请添加 static 修饰符(或 static public,如果您在框架中声明它)。使用 static 您将创建变量的单个实例,与您的类的任何特定实例无关(一个且只有一个 metadataObj 实例在您的类的所有实例之间共享)。如果您从不同的线程访问 metadataObj,请小心……您可能会遇到非常烦人的故障,并且难以修复。在后一种情况下,请考虑线程同步(不完全是一个容易处理的主题)......如果您对自己需要做什么没有一个非常清楚的想法,我会不鼓励这样做。相反,如果您只需要在类范围内使用它(我的意思是,供所有成员函数使用......并且只有它们),请将它放在 Alec 告诉您的地方。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-03-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多