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

时间:2015-03-24 08:48:22

标签: ios swift bluetooth core-bluetooth

我是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 个答案:

答案 0 :(得分:8)

如果您在创建value时指定了非零[{1}},那么它就是一个“缓存”特征'并且正如错误消息所示,您以后无法更改该值。

来自CBMutableCharacteristic CBMutableCharacteristic方法的文档 -

  

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

在您创建init时指定nil - 您可以在CBMutableCharacteristic didReceiveReadRequest方法中提供请求时提供值。

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

请务必阅读Core Bluetooth Programming Guide

中的执行常见外设角色任务部分

答案 1 :(得分:0)

我找到了一个坚实的帖子,其中包含大量用于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