【问题标题】:CoreBluetooth Characteristic value being overwritten to nilCoreBluetooth 特征值被覆盖为零
【发布时间】:2018-06-19 08:57:02
【问题描述】:

我已经创建了一个蓝牙代理并且蓝牙连接正确。

在我的蓝牙对象中,我调用了所需的函数:

// Characteristic being targeted
var writeCharacteristic: CBCharacteristic!

public func peripheral(_ peripheral: CBPeripheral, 
    didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    guard let characteristics = service.characteristics else {
        return
    }
    print(characteristics)
    for characteristic in characteristics {
        switch (characteristic.uuid) {
        case (serialUUID) :
            print("serialPortRXCharacterUUID: \(service.uuid)")
            writeCharacteristic = characteristic  
        default:
            print("nothing")
        }
    }
}

检查调试器 writeCharacteristic 存储正确的特征,但是当我在 ViewController 中调用 writeToDevice 时。

// View Controllers function
@IBAction func writeToDevice(_ sender: UIButton) {
    bluetoothManager.writeToPeripheral(message: "Test", peripheral: peripheral)
}

writeToDevice 函数在蓝牙类对象中被调用如下:

func writeToPeripheral(message: String, peripheral: CBPeripheral) {
    if let data = message.data(using: String.Encoding.utf8) {
        let datareturn = String(bytes: data, encoding: .utf8)
        print(writeCharacteristic)
        peripheral.writeValue(data, for: writeCharacteristic!, type: .withoutResponse)
    }
}

在设备连接时,调试器 writeCharacteristic 从一个值开始,但在我从另一个视图控制器调用按钮后,writeCharacteristic 似乎又回到了nil

【问题讨论】:

  • 您确定您使用的是同一个蓝牙类实例吗?
  • @Paulw11 我确实在这个新的 ViewController 中再次调用了 BluetoothLE.init(),然后将其委托给“新 ViewControllers”的自我。我猜这会创建一个新实例,不是吗?...
  • 确实如此。我建议为您的 BluetoothLE 使用 Singleton。
  • 你能检查是否包含像 writeCharacteristic.properties.contains(.write) 这样的写权限吗?

标签: ios iphone swift swift4 core-bluetooth


【解决方案1】:

根据@Larme 的评论,我意识到我正在创建 BLE 对象的第二个实例,因此实现单例模式将解决此问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-09
    • 2018-04-11
    • 1970-01-01
    • 2016-12-27
    • 2013-09-02
    • 1970-01-01
    相关资源
    最近更新 更多