You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift Playground中VNDetectBarcodesRequest执行报错求助

Swift Playground条码识别代码报错排查

我在Swift Playground中参照主流教程编写了一段简洁的条码识别代码,但执行时VNDetectBarcodesRequest触发错误,代码进入catch分支(控制台打印error here❌),请帮忙排查原因。

代码如下:

import UIKit
@preconcurrency import Vision
var queue = DispatchQueue.global()
extension UIImage {
    @MainActor func detectBarcodes(completion: @Sendable @escaping ([VNBarcodeObservation]) ->()) {
        let request = VNDetectBarcodesRequest()
        request.queueFor(image: self) { result in
            completion(result as? [VNBarcodeObservation] ?? [])
        }
    }
}

extension VNDetectBarcodesRequest {
    @MainActor func queueFor(image: UIImage, completion: @Sendable @escaping ([Any]?) -> ()) {
        let handler = VNImageRequestHandler(cgImage: image.cgImage!, orientation: .up, options: [:])
        queue.async {
            do {
                let w = "ok here 1✅"
                try handler.perform([self])
                let b = "ok here 2✅"
            } catch {
                let c = "error here❌" //<== this line is printed on console. Why?
            }
        }
    }
}
let image = UIImage(named: "5.jpg")!
image.detectBarcodes { barcodes in
    for barcode in barcodes {
        let a = barcode.payloadStringValue
    }
}

报错截图:

报错截图

测试图片:

测试条码图片

内容的提问来源于stack exchange,提问作者kunass2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 10:32:32