如何在方法之间传递潜在的错误

How to pass potential error between methods

我正在尝试包装 Core Bluetooth Peripheral 方法以便在 React Native 中使用。它与已经完成的 android 代码对应,因此 API 已设置。

当我打电话给 CBPeripheralManager.addService 时,我需要履行或拒绝 javascript 方面的承诺。

问题是,Core Bluetooth 没有为该方法提供回调,似乎需要 private func peripheralManager(_ peripheral: CBPeripheralManager, didAddService service: CBService, error: Error?)

我是 iOS 和 Swift 的新手,所以我觉得这种行为很奇怪。有什么想法可以包装函数以便正确处理错误报告吗?

谢谢

class BLE: NSObject, CBPeripheralManagerDelegate {
    var advertising: Bool = false
    var servicesMap = Dictionary<String, CBMutableService>()
    var manager: CBPeripheralManager!

    override init() {
        super.init()
        manager = CBPeripheralManager(delegate: self, queue: nil, options: nil)
    }

    func addService(promise, serviceUUID) {
        let serviceUUID = CBUUID(string: uuid)
        let service = CBMutableService(type: serviceUUID, primary: true)
        manager.add(service)
    }

    private func peripheralManager(_ peripheral: CBPeripheralManager, didAddService service: CBService, error: Error?) {
        if let error = error {
            // this should reject the addService promise
            return
        }
        // this should fulfill the promise
    }    
}

不清楚 promise 的类型是什么,但您需要将其存储在某处,稍后再执行。例如,您可以添加 属性:

var pendingServices: [CBUUID: Promise] = [:]

(我不知道你承诺的类型真的在这里)

然后将其存储在 addService:

assert(pendingServices[serviceUUID] == nil)
pendingServices[serviceUUID] = promise

稍后在(正确的;请参阅我的评论)委托方法中,您将处理它:

if let promise = pendingServices.removeValue(forKey: service.uuid) {
    promise.fulfill() // Or whatever you do with it
}