Ios CoreBooth特征值被覆盖为零

Ios CoreBooth特征值被覆盖为零,ios,iphone,swift,swift4,core-bluetooth,Ios,Iphone,Swift,Swift4,Core Bluetooth,我已经创建了蓝牙代理,并且蓝牙连接正确 在我的Bluetooth对象中,我调用了所需的函数: // Characteristic being targeted var writeCharacteristic: CBCharacteristic! public func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {

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

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

// 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中调用
writeDevice

// View Controllers function
@IBAction func writeToDevice(_ sender: UIButton) {
    bluetoothManager.writeToPeripheral(message: "Test", peripheral: peripheral)
}
在Bluetooth类对象中调用
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
似乎在@Larme的注释后返回到
nil

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

您确定使用的是Bluetooth类的同一个实例吗?@Paulw11我确实在这个新的ViewController中再次调用BluetoothLE.init(),然后将其委托给“新的ViewController”自己。我猜这会创建一个新的实例,不是吗?…的确。我建议对您的
Bluetooth
使用单例。您是否可以检查是否包含writeCharacteristic.properties.contains(.write)这样的写入权限?