CoreBluetooth系列教程(六):SwiftyBluetooth的使用

SwiftyBluetoothSwift中封裝CoreBluetooth框架的一個開源庫SwiftyBluetooth,個人覺得比較好用,是對CoreBluetooth的封裝,可自行查看代碼,下面來講講它的使用。
首先需要判斷藍牙打開的狀態(tài),藍牙打開了才可進行下一步:

     SwiftyBlutooth.asyncState { state in
            switch state {
            case .poweredOn:
                print("藍牙打開了,去搜索要連接設備")
             break

            case .poweredOff:
                print("藍牙未打開,添加提示")
                break
            default:
                break

            }
        }

第二步,搜索藍牙設備

// withServiceUUIDs:需要搜索的設備`CBUUID`數(shù)組,默認為nil,則搜索附近所有的藍牙設備,浪費時間,所以最好傳入`[CBUUIDConvertible]`
// timeoutAfter 搜索時長
SwiftyBluetooth.scanForPeripherals(withServiceUUIDs: nil, timeoutAfter: 15) { scanResult in
    switch scanResult {
        case .scanStarted:
            // The scan started meaning CBCentralManager scanForPeripherals(...) was called 
        case .scanResult(let peripheral, let advertisementData, let RSSI):
            // 解析`advertisementData`,找到要連接的設備,然后連接設備 
            self.peripheral = peripheral
        case .scanStopped(let error):
            // The scan stopped, an error is passed if the scan stopped unexpectedly
    }
}        

第三步,連接設備

   guard let peripheral = self.peripheral  else { return }
        // 開始連接設備
   peripheral.connect(withTimeout: time) {  result in
            switch result {
            case .success:  
                //連接成功,
                break      
            case .failure(let error):
                break
            }
        }

設備連接成功后,就可以進行readValue、setNotifyValue、writeValue的操作了,有不明白的同學可參考我這篇文章。剩余常用的API如下:

peripheral.discoverServices(withUUIDs: nil) { result in
    switch result {
    case .success(let services):
        break // An array containing all the services requested
    case .failure(let error):
        break // A connection error or an array containing the UUIDs of the services that we're not found
    }
}
peripheral.discoverCharacteristics(withUUIDs: nil, ofServiceWithUUID: "180A") { result in
    // The characteristics discovered or an error if something went wrong.
    switch result {
    case .success(let services):
        break // An array containing all the characs requested.
    case .failure(let error):
        break // A connection error or an array containing the UUIDs of the charac/services that we're not found.
    }
}

參考資料:

https://github.com/jordanebelanger/SwiftyBluetooth
http://m.itdecent.cn/p/6feab1912f8c

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容