swift - 如何正确设置委托(delegate)属性? ( swift )

标签 swift delegates

我正在尝试将 SQLClient 实现到现有的 iOS 应用程序中。该应用程序是一个条形码阅读器,可通过 LAN 向数据库发出 INSERT。 SQLClient 的委托(delegate)属性必须设置为 NSObject 才能进行错误处理,但我在设置它时遇到了问题。 我的实现问题出现在最后一个方法中,found

首先,Xcode 希望我向下转换为更具体的类型。在采纳 Xcode 的建议并将 client as Anyobject 转换后,我得到了 Ambigously use of delegate

所以,简而言之,我需要帮助设置 SQLClient 的委托(delegate)属性,以便我可以触发插入。我愿意了解你们是否可以推荐资源或提供指导。

SQLClient --> https://github.com/martinrybak/SQLClient

//
//  QRScannerController.swift
//  QRCodeReader
//
//  Created by Simon Ng on 13/10/2016.
//  Copyright © 2016 AppCoda. All rights reserved.
//

import UIKit
import AVFoundation


class QRScannerController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {

    @IBOutlet var messageLabel:UILabel!
    @IBOutlet var topbar: UIView!

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

    let supportedCodeTypes = [AVMetadataObjectTypeUPCECode,
                        AVMetadataObjectTypeCode39Code,
                        AVMetadataObjectTypeCode39Mod43Code,
                        AVMetadataObjectTypeCode93Code,
                        AVMetadataObjectTypeCode128Code,
                        AVMetadataObjectTypeEAN8Code,
                        AVMetadataObjectTypeEAN13Code,
                        AVMetadataObjectTypeAztecCode,
                        AVMetadataObjectTypePDF417Code,
                        AVMetadataObjectTypeQRCode]

    override func viewDidLoad() {
        super.viewDidLoad()



        // Get an instance of the AVCaptureDevice class to initialize 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)

            // Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
            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()

            // Move the message label and top bar to the front
            view.bringSubview(toFront: messageLabel)
            view.bringSubview(toFront: topbar)

            // 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)
                view.bringSubview(toFront: qrCodeFrameView)
            }

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

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


    // MARK: - AVCaptureMetadataOutputObjectsDelegate Methods

    func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
        captureSession?.stopRunning()
        // 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 the 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 bounds
            let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj)
            qrCodeFrameView?.frame = barCodeObject!.bounds

            if metadataObj.stringValue != nil {
                messageLabel.text = metadataObj.stringValue
                print(metadataObj.stringValue)
                found(code: metadataObj.stringValue)

            }
        }
    }

    func found(code: String) {
        print(code)
        /*
         Fire off the QR code to the database
        */
        let client = SQLClient.sharedInstance()!
        client.delegate = client.self

    }
}

最佳答案

这最终成为我遗漏的部分。

扩展QRScannerController:SQLClientDelegate { func error(_ 错误:字符串!,代码:Int32,严重性:Int32) { 打印(错误) } }

关于swift - 如何正确设置委托(delegate)属性? ( swift ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330913/

相关文章:

SwiftUI 和 Mac 催化剂 : Sidebar is not displayed correctly

objective-c - block 与委托(delegate)

c# - 在方法中创建委托(delegate)类型

ios - 将 UITableView 委托(delegate)和数据源与 tableViewController 分离

iphone - 委托(delegate)覆盖

ios - Swift 2.0 中的 supportedInterfaceOrientations() 错误

ios - 如何使用 UIBezierPath 更改元素的颜色?

swift - RxSwift - withLatestFrom 结合来自两个可观察值的值

swift - 如何沿水平线移动 SKSpriteNode

c# - 使用委托(delegate)来避免子类化