Home Articles

在Core Bluetooth Framework中创建Writable特性的问题

Asked
Viewed 909 times
4

我是Core Bluetooth Framework的新手 . 我正在开发一个充当外围设备的应用程序 . 我需要应用程序通知特定值到订阅的中心,并且还通过连接的中心写出特征值 . 我在创建它时设置了特征值 . 问题是当我设置要通知或写入的特性属性时显示错误“具有缓存值的特征必须是只读的” . 有谁能够帮我 ?

var charValue = characteristicDetail["value"] as String
 var charProperties:CBCharacteristicProperties = getProperty(characteristicDetail["properties"] as String )
 let data = charValue.dataUsingEncoding(NSUTF8StringEncoding)
 var characteristic = CBMutableCharacteristic(type: charId, properties: charProperties, value: data, permissions: CBAttributePermissions.Readable)



func getProperty(string:String) -> CBCharacteristicProperties
    {
    var propertyString:CBCharacteristicProperties?
    switch string{
    case "r","R":
        propertyString = CBCharacteristicProperties.Read
    case "w","W":
        propertyString = CBCharacteristicProperties.Write
    case "n","N":
        propertyString = CBCharacteristicProperties.Notify
    case "i","I":
        propertyString = CBCharacteristicProperties.Indicate
    case "rw","wr","WR","RW":
        propertyString = CBCharacteristicProperties.Read|CBCharacteristicProperties.Write
    case "rn","nr","NR","RN":
        propertyString = CBCharacteristicProperties.Read|CBCharacteristicProperties.Notify
    case "wn","nw","NW","WN":
        propertyString = CBCharacteristicProperties.Write|CBCharacteristicProperties.Notify
    default:
        propertyString = CBCharacteristicProperties.Read
    }
    return propertyString!

}

2 Answers

  • 8

    我找到了一个坚实的帖子中,在BLE方面包含了大量用于不同任务的优秀片段:

    创建服务:

    let serviceUUID = CBUUID(string: kServiceUUID)
    let service = CBMutableService(type: serviceUUID, primary: true)
    

    创造特色:

    let characteristicUUID = CBUUID(string: kCharacteristicUUID)
    let properties: CBCharacteristicProperties = [.Notify, .Read, .Write]
    let permissions: CBAttributePermissions = [.Readable, .Writeable]
    let characteristic = CBMutableCharacteristic(
        type: characteristicUUID,
        properties: properties,
        value: nil,
        permissions: permissions)
    

    为服务添加特征:

    service.characteristics = [characteristic1, characteristic2]
    

    将服务添加到外围设备管理器:

    peripheralManager.addService(service)
    

    Source

  • 0

    如果在创建 CBMutableCharacteristic 时指定了非零 value ,那么它是'cached characteristic',并且如错误消息所示,您以后无法更改该值 .

    CBMutableCharacteristic init 方法的文档 -

    value - 要缓存的特征值 . 如果为零,则该值为动态值,将根据需要进行请求 .

    创建 CBMutableCharacteristic 时指定 nil - 在 didReceiveReadRequest CBPeripheralManagerDelegate 方法中请求时提供值 .

    如果您有已订阅特征的中心,那么每当值发生变化时,您也应该在 CBPeripheralManager 上调用 updateValue .

    请务必阅读Core Bluetooth Programming Guide中执行常见外设角色任务一节

Related