代码如下:
ScanViewController.swift:
import UIKit
import DynamsoftCameraEnhancer
import DynamsoftCaptureVisionRouter
import DynamsoftBarcodeReader
import DynamsoftCore
import DynamsoftLicense
// UTS内置对象的引用
import DCloudUTSFoundation
class ScanViewController: UIViewController, CapturedResultReceiver, LicenseVerificationListener {
var cameraView:CameraView!
let dce = CameraEnhancer()
let cvr = CaptureVisionRouter()
weak var delegate: DataFetchDelegate?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setLicense()
setUpCamera()
setUpDCV()
console.log("scan view did loaded.delegate:",delegate)
}
override func viewWillAppear(_ animated: Bool) {
dce.open()
// Start capturing when the view will appear. If success, you will receive results in the CapturedResultReceiver.
cvr.startCapturing(PresetTemplate.readSingleBarcode.rawValue) { isSuccess, error in
if (!isSuccess) {
if let error = error {
self.showResult("Error", error.localizedDescription)
}
}
}
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
dce.close()
cvr.stopCapturing()
dce.clearBuffer()
super.viewWillDisappear(animated)
}
func setLicense() {
// Initialize the license.
// The license string here is a trial license. Note that network connection is required for this license to work.
// You can request an extension via the following link: https://www.dynamsoft.com/customer/license/trialLicense?product=dbr&utm_source=samples&package=ios
LicenseManager.initLicense("", verificationDelegate: self)
}
func displayLicenseMessage(message: String) {
let label = UILabel()
label.text = message
label.textAlignment = .center
label.numberOfLines = 0
label.textColor = .red
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
NSLayoutConstraint.activate([
label.centerXAnchor.constraint(equalTo: view.centerXAnchor),
label.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
label.leadingAnchor.constraint(greaterThanOrEqualTo: view.leadingAnchor, constant: 20),
label.trailingAnchor.constraint(lessThanOrEqualTo: view.trailingAnchor, constant: -20)
])
}
func setUpCamera() {
cameraView = .init(frame: view.bounds)
cameraView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
view.insertSubview(cameraView, at: 0)
dce.cameraView = cameraView
}
func setUpDCV() {
// Set the camera enhancer as the input.
try! cvr.setInput(dce)
// Add CapturedResultReceiver to receive the result callback when a video frame is processed.
cvr.addResultReceiver(self)
}
// Implement the callback method to receive DecodedBarcodesResult.
// The method returns a DecodedBarcodesResult object that contains an array of BarcodeResultItems.
// BarcodeResultItems is the basic unit from which you can get the basic info of the barcode like the barcode text and barcode format.
func onDecodedBarcodesReceived(_ result: DecodedBarcodesResult) {
console.log("onDecodedBarcodesReceived,self.delegate start:",self.delegate)
if let items = result.items, items.count > 0 {
DispatchQueue.main.async {
self.cvr.stopCapturing()
self.dce.clearBuffer()
}
var message = ""
for item in items {
// Extract the barcode format and the barcode text from the BarcodeResultItem.
message = String(format:"\nFormat: %@\nText: %@\n", item.formatString, item.text)
console.log("onDecodedBarcodesReceived,self.delegate end:",self.delegate)
self.delegate?.didReceiveData(item.text)
console.log("scaned:",item.text)
}
showResult("Results", message) {
// Restart the capture
self.cvr.startCapturing(PresetTemplate.readSingleBarcode.rawValue)
}
}
}
// MARK: LicenseVerificationListener
func onLicenseVerified(_ isSuccess: Bool, error: Error?) {
if !isSuccess {
if let error = error {
print("\(error.localizedDescription)")
DispatchQueue.main.async {
self.displayLicenseMessage(message: "License initialization failed:" + error.localizedDescription)
}
}
}
}
private func showResult(_ title: String, _ message: String?, completion: (() -> Void)? = nil) {
DispatchQueue.main.async {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { _ in completion?() }))
self.present(alert, animated: true, completion: nil)
}
}
}
ParentViewController.uts代码
import { UTSiOS } from "DCloudUTSFoundation"
export class ParentViewController implements DataFetchDelegate {
viewDidAppear() {
let asyncVC = ScanViewController()
asyncVC.delegate = this
UTSiOS.getCurrentViewController().present(asyncVC, animated = true, completion = null)
}
@objc didReceiveData(data : string) {
console.log("收到数据:" + data)
}
}
DataFetchDelegate.swift代码:
protocol DataFetchDelegate: AnyObject {
func didReceiveData(_ data: String)
}
日志如下:
10:35:50.447 App Launch at App.vue:4
10:35:50.448 App Show at App.vue:7
10:35:57.509 testScanCodeListener at pages/index/index.vue:24
10:35:57.511 open scan view at uni_modules/ula-barscan/utssdk/app-ios/index.uts:5
10:35:57.511 scan view did loaded.delegate: [ParentViewController] { ... }
10:36:18.985 onDecodedBarcodesReceived,self.delegate start: null
10:36:18.986 onDecodedBarcodesReceived,self.delegate end: null
10:36:18.986 scaned: QA1106QQ558
10:36:21.094 App Hide at App.vue:10
目前遇到的问题是:为什么调用代理方法时,delegate是空的呢,在view did loaded方法里面显示的是有值的,到用的时候为什么是 null 了?
4 个回复
DerekZ (作者)
没大佬回答吗
DCloud_iOS_LZY
1、可以在swift代码里发送通知,或者使用使用代理,在uts代码中接收通知,或这实现代理方法。
2、uts代码编译成swift,这些功能都是支持的,原生怎么写,uts就怎么写,对应转换一下语法就行。
3、如果你想将扫到的内容传给vue页面,可以在uts中定义一个带callback参数的api,在callback中将结果回传。
DerekZ (作者)
感谢大佬回复,能帮我写一个 demo 吗,我试了,遇到很多问题,目前还没解决。非常感谢
2024-11-27 14:33
DerekZ (作者)
代码如下:
ScanViewController.swift:
import UIKit
import DynamsoftCameraEnhancer
import DynamsoftCaptureVisionRouter
import DynamsoftBarcodeReader
import DynamsoftCore
import DynamsoftLicense
// UTS内置对象的引用
import DCloudUTSFoundation
class ScanViewController: UIViewController, CapturedResultReceiver, LicenseVerificationListener {
}
ParentViewController.uts代码
import { UTSiOS } from "DCloudUTSFoundation"
export class ParentViewController implements DataFetchDelegate {
}
DataFetchDelegate.swift代码:
protocol DataFetchDelegate: AnyObject {
func didReceiveData(_ data: String)
}
日志如下:
10:35:50.447 App Launch at App.vue:4
10:35:50.448 App Show at App.vue:7
10:35:57.509 testScanCodeListener at pages/index/index.vue:24
10:35:57.511 open scan view at uni_modules/ula-barscan/utssdk/app-ios/index.uts:5
10:35:57.511 scan view did loaded.delegate: [ParentViewController] { ... }
10:36:18.985 onDecodedBarcodesReceived,self.delegate start: null
10:36:18.986 onDecodedBarcodesReceived,self.delegate end: null
10:36:18.986 scaned: QA1106QQ558
10:36:21.094 App Hide at App.vue:10
目前遇到的问题是:为什么调用代理方法时,delegate是空的呢,在view did loaded方法里面显示的是有值的,到用的时候为什么是 null 了?
DCloud_iOS_LZY
ParentViewController 是在哪创建的?怎么创建的?得保证这个控制器不被提前释放
DerekZ (作者)
vue 中点击 button时,如下代码创建的
let scanView = ParentViewController()
scanView.viewDidAppear()
2024-11-30 01:17