Set metadata types after session starts (availableMetadataObjectTypes empty before)
This commit is contained in:
parent
e87921b59f
commit
b929b1eb6e
@ -155,22 +155,6 @@ class QRScannerWindowController: NSObject, AVCaptureMetadataOutputObjectsDelegat
|
||||
if session.canAddOutput(output) {
|
||||
session.addOutput(output)
|
||||
output.setMetadataObjectsDelegate(self, queue: .main)
|
||||
// 检查摄像头是否支持 QR 码识别
|
||||
if output.availableMetadataObjectTypes.contains(.qr) {
|
||||
output.metadataObjectTypes = [.qr]
|
||||
output.rectOfInterest = CGRect(x: 0.1, y: 0.1, width: 0.8, height: 0.8)
|
||||
} else {
|
||||
// fallback: 支持什么就用什么
|
||||
let types = output.availableMetadataObjectTypes.filter { $0 == .qr || $0 == .ean13 || $0 == .ean8 || $0 == .code128 }
|
||||
if !types.isEmpty {
|
||||
output.metadataObjectTypes = types
|
||||
} else {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.showError("Camera does not support QR code scanning")
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let previewLayer = AVCaptureVideoPreviewLayer(session: session)
|
||||
@ -181,7 +165,6 @@ class QRScannerWindowController: NSObject, AVCaptureMetadataOutputObjectsDelegat
|
||||
// 回到主线程更新 UI
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
guard let self = self, previewHost.window != nil else {
|
||||
// 窗口已关闭,停止
|
||||
session.stopRunning()
|
||||
return
|
||||
}
|
||||
@ -196,6 +179,24 @@ class QRScannerWindowController: NSObject, AVCaptureMetadataOutputObjectsDelegat
|
||||
// 启动会话(后台启动避免阻塞)
|
||||
DispatchQueue.global(qos: .userInitiated).async {
|
||||
session.startRunning()
|
||||
|
||||
// session 启动后再设置 metadata types(启动前 availableMetadataObjectTypes 可能为空)
|
||||
if session.canAddOutput(output) == false,
|
||||
output.availableMetadataObjectTypes.contains(.qr) {
|
||||
output.metadataObjectTypes = [.qr]
|
||||
} else {
|
||||
// 尝试设置所有支持的类型
|
||||
let available = output.availableMetadataObjectTypes
|
||||
if available.contains(.qr) {
|
||||
output.metadataObjectTypes = [.qr]
|
||||
} else if !available.isEmpty {
|
||||
output.metadataObjectTypes = available
|
||||
} else {
|
||||
DispatchQueue.main.async { [weak self] in
|
||||
self?.showError("Camera does not support QR scanning. Check System Settings → Privacy → Camera.")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user