SwiftyBluetooth是Swift中封裝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