如何更改在使用core bleutooth ios扫描外围设备时发现的特征ID的顺序



我在ios中使用核心蓝牙框架,扫描并发现2个特征ID,但我希望它们的顺序与我得到的不同,所以可以通过编程更改它们的顺序吗?

代码

   if (service.UUID.isEqual(CBUUID.UUIDWithString("F4F2-BC76-3206341A")))
    {
        println(service.characteristics.count)
        for aChar:CBCharacteristic in service.characteristics as [CBCharacteristic]
        {
            println(aChar)
            println(aChar.UUID)
            /* Write data*/
            if aChar.UUID.isEqual(CBUUID.UUIDWithString("D0F0AECD-6405-0B040047"))
            {
                var str:NSString = "heyaa..!!"
                data = str.dataUsingEncoding(NSUTF8StringEncoding)!
                peripheral.writeValue(data, forCharacteristic: aChar, type: CBCharacteristicWriteType.WithResponse)
                println("Write performed")
            }
            /* read data  */
            if aChar.UUID.isEqual(CBUUID.UUIDWithString("C8853E-A248-C6F0B1"))
            {
                peripheral.readValueForCharacteristic(aChar)
                println("Read performed")
            }
        }
    }

在这个特性中,读取数据的ID首先被调用,但我想首先调用写入数据的特性ID,所以有什么方法可以解决。请帮帮我。提前谢谢。

特性将以任意和未定义的顺序被发现,但这并不重要。

您应该存储对发现的特征的引用,以便根据需要对其进行写入。

你的应用程序应该经过不同的阶段

  1. 扫描并发现广告特定服务的外围设备
  2. 连接到目标外围设备
  3. 了解服务的特点
  4. 根据需要读取/写入数据-根据需要重复此步骤
  5. 断开连接

例如:

    var writeCharacteristic : CBCharacteristic?
    var readCharacteristic : CBCharacteristic?
    optional func peripheral(_ peripheral: CBPeripheral!, didDiscoverCharacteristicsForService service: CBService!,error error: NSError!) {    
      if (service.UUID.isEqual(CBUUID.UUIDWithString("F4F2-BC76-3206341A"))) 
      {
        println(service.characteristics.count)
        for aChar:CBCharacteristic in service.characteristics as [CBCharacteristic]
        {
            println(aChar)
            println(aChar.UUID)
            /* Write data*/
            if aChar.UUID.isEqual(CBUUID.UUIDWithString("D0F0AECD-6405-0B040047"))
            {
                self.writeCharacteristic=aChar
            }
            else if aChar.UUID.isEqual(CBUUID.UUIDWithString("C8853E-A248-C6F0B1"))
            {
                self.readCharacteristic=aChar
            }
        }
      }
      if (self.writeCharacteristic != nil && self.readCharacteristic != nil) {
            var str:NSString = "heyaa..!!"
            data = str.dataUsingEncoding(NSUTF8StringEncoding)!
            peripheral.writeValue(data, forCharacteristic: self.writeCharacteristic!, type: CBCharacteristicWriteType.WithResponse)
            println("Write performed")
      }
    }
    optional func peripheral(_ peripheral: CBPeripheral!,didWriteValueForCharacteristic characteristic: CBCharacteristic!,error error: NSError!) {
       peripheral.readValueForCharacteristic(self.readCharacteristic!)
       println("Read performed")
    }

最新更新