2016-03-14 89 views
0

我綁連接到藍牙硬件,但我不能得到一個通知,當值被更新,讀讀書,這裏是我的代碼:無法寫入或讀取CBPeripheral | CBMutableCharacteristic

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { 

    guard peripheral == self.peripheral && error == nil else { 
     return 
    } 

    if let characteristics = service.characteristics { 
     for characteristic in characteristics { 
      if characteristic.UUID == QuadrarCharacteristicUUID { 
       if let peripheral = self.peripheral { 
        self.quadrarCharacteristic = CBMutableCharacteristic(type: QuadrarCharacteristicUUID, 
         properties: [.Read, .Write, .Notify], 
         value: nil, 
         permissions: [.Readable, .Writeable]) 
        self.quadrarCharacteristic?.descriptors = characteristic.descriptors 
        peripheral.setNotifyValue(true, forCharacteristic: self.quadrarCharacteristic!) 
       } 
      } 
     } 
    } 
} 

,當我寫作:

func writeBytes() { 
      self.quadrarCharacteristic!.service.peripheral.writeValue(self.bytesToWriteArray[self.senderCounter], 
      forCharacteristic: self.quadrarCharacteristic!, type: CBCharacteristicWriteType.WithResponse) 
    } 

我知道,即使是寫不工作,因爲

func peripheral(peripheral: CBPeripheral, didWriteValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) 

不被稱爲... 但如果我只用了

var quadrarCharacteristic: CBCharacteristic? 

,並嘗試寫出來,作爲一個非CBMutableCharacteristic,它的工作原理,但我不能得到通知工作...

回答

2

不創建一個新的CBMutableCharacteristic當你作爲一箇中心,您只需使用所提供給您的CBCharacteristic對象didDiscoverCharacteristicsForService -

func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) { 

    guard peripheral == self.peripheral && error == nil else { 
     return 
    } 

    if let characteristics = service.characteristics { 
     for characteristic in characteristics { 
      if characteristic.UUID == QuadrarCharacteristicUUID { 
       self.quadrarCharacteristic=charateristic 
       peripheral.setNotifyValue(true, forCharacteristic: self.quadrarCharacteristic!) 
       } 
      } 
     } 
    } 
} 

此外,你需要確認你的特點是支持通知。