2017-07-14 96 views
0

我想讓兩個運行在不同設備上的程序通過藍牙與CoreBluetooth進行通信。我可以找到並連接來自經理的外圍設備,並且可以瀏覽連接的外圍設備中的服務,但是當我嘗試並嘗試發現特徵時,出現錯誤The specified UUID is not allowed for this operation.,並且如預期的那樣,該服務的特徵爲零。UUID不允許在外設didDiscoverCharacteristicsfor服務

這是什麼意思?我試圖通過指定目標的UUID而沒有發現特徵,都顯示此錯誤。

這是打印錯誤的功能。

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) { 
    print(error.localizedDescription)//prints "The specified UUID is not allowed for this operation." 
    if service.characteristics != nil { 
     for characteristic in service.characteristics! { 
      if characteristic.uuid == CBUUID(string: "A4389A32-90D2-402F-A3DF-47996E123DC1") { 
       print("characteristic found") 
       peripheral.readValue(for: characteristic) 
      } 
     } 
    } 
} 

這是我尋找外圍設備的地方。

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { 
    if peripheral.services != nil { 
     for service in peripheral.services! { 
      if service.uuid == CBUUID(string: "dc495108-adce-4915-942d-bfc19cea923f") { 
       peripheral.discoverCharacteristics(nil, for: service) 
      } 
     } 
    } 
} 

這是我如何在其他設備上添加服務特性。

service = CBMutableService(type: CBUUID(string:"dc495108-adce-4915-942d-bfc19cea923f"), primary: true) 
characteristic = CBMutableCharacteristic(type: CBUUID(string: "A4389A32-90D2-402F-A3DF-47996E123DC1"), properties: .write, value: nil, permissions: .writeable) 
service.characteristics = [characteristic] 

我嘗試了許多不同的屬性和權限組合(包括.read/.readable),我得到了同樣的錯誤。

+0

您試圖讀取您已設置爲只寫因此當您嘗試獲得錯誤的特性並閱讀它。 – Paulw11

+0

有道理,但我如何使它可讀寫?我也將屬性更改爲.read和.read權限,並且它不會更改任何內容。 – C1FR1

回答

0

您正試圖讀取您設置爲只寫的特性的值,因此Core Bluetooth會給出錯誤;對的讀操作對於指定的特性無效。

如果你希望你的特點是可讀可寫的,你需要指定此:

service = CBMutableService(type: CBUUID(string:"dc495108-adce-4915-942d-bfc19cea923f"), primary: true) 
let characteristic = CBMutableCharacteristic(type: CBUUID(string: "A4389A32-90D2-402F-A3DF-47996E123DC1"), properties: [.write, .read], value: nil, permissions: [.writeable, .readable]) 
service.characteristics = [characteristic] 
+0

我已經試過這個,沒有幫助。 – C1FR1

+0

你從哪裏得到錯誤打印?我剛剛創建了一個使用你的代碼的測試應用程序,它工作正常。這裏是我的兩個視圖控制器 - 第一個是中心,第二個是外圍設備https://gist.github.com/paulw11/5d734957ddd575f9d00c758926984e76 – Paulw11

+0

錯誤來自'didDiscoverCharacteristicsFor服務'功能,我將編輯問題以顯示哪裏。我查看了您的測試應用程序,並且使用了另一種搜索外設的方式(可能還有更好的方法),所以我將其複製並解決了問題。一旦連接,中央運行'didDiscoverCharacteristicsFor'函數幾次,有時會有錯誤,如果沒有,特性將顯示爲零。那麼它會再運行一次,並在for語句中崩潰,說'NSArray元素無法匹配Swift數組元素類型。 – C1FR1