[swift]CoreBluetooth(Service)

閱讀時間約 9 分鐘

CBCentralManager:藍芽管理中心,做外部設備搜尋、連接。

CBPeripheral:外部設備

CBCharacteristic:外部設備的特徵。


首先要在info.plist裡設定新增藍芽服務。然後做宣告,如下:

var centralManager: CBCentralManager = CBCentralManager.init(delegate: self, queue: .main)


判斷手機藍牙狀態:

// 判斷手機藍牙狀態
func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .resetting:
print("resetting")
case .unsupported:
print("unsupported")
case .unauthorized:
print("unauthorized")
case .poweredOff:
print("poweredOff")
case .poweredOn:
print("poweredOn")
central.scanForPeripherals(withServices: [CBUUID.init(string: service_UUID)], options: nil)
default:
print("unknown")
}
}


發現符合要求的外設:

/** 發現符合要求的外設 */
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
self.peripheral = peripheral
// 根據外設名稱來過濾
// if (peripheral.name?.hasPrefix("WH"))! {
// central.connect(peripheral, options: nil)
// }
self.centralManager?.stopScan()
central.connect(peripheral, options: nil)
}


連接成功的回調:

/** 連接成功 */
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
peripheral.discoverServices([CBUUID.init(string: service_UUID)])
print("連接成功")
}


連接失敗的回調:

/** 連接失敗的回調 */
func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
print("連接失敗")
}


斷開連接的回調:

/** 斷開連接 */
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("斷開連接")
// 重新連接
central.connect(peripheral, options: nil)
}


發現服務的回調:

/** 發現服務 */
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
for service: CBService in peripheral.services! {
print("外設中的服務有:\(service)")
}

//本例的外設中只有一個服務
let service = peripheral.services?.last

// 根據UUID尋找服務中的特徵
peripheral.discoverCharacteristics([CBUUID.init(string: characteristic_UUID)], for: service!)
}


發現特徵的回調:

/** 發現特徵 */
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
for characteristic: CBCharacteristic in service.characteristics! {
print("外設中的特徵有:\(characteristic)")
}
self.characteristic = service.characteristics?.last

// 讀取特徵裏的數據
peripheral.readValue(for: self.characteristic!)

// 訂閱
peripheral.setNotifyValue(true, for: self.characteristic!)
}


訂閱狀態的回調:

/** 訂閱狀態 */
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
if let error = error {
print("訂閱失敗: \(error)")
return
}

if characteristic.isNotifying {
print("訂閱成功")
} else {
print("取消訂閱")
}
}


接收到數據的回調:

/** 接收到數據 */
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let data = characteristic.value
print(String.init(data: data!, encoding: String.Encoding.utf8)!)
}


主動傳送:

//主動傳送
func didClickPost(_ sender: Any) {
self.peripheral?.writeValue(Data(), for: self.characteristic!, type: CBCharacteristicWriteType.withResponse)
}


寫入數據:

/** 寫入數據 */
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
print("寫入數據")
}


主動接收:

//主動接收
func didClickGet(_ sender: Any) {
self.peripheral?.readValue(for: self.characteristic!)
}



8會員
118Content count
嗨,我是一名程式設計師,會在這分享開發與學習紀錄。
留言0
查看全部
發表第一個留言支持創作者!
小黑與程式的邂逅 的其他內容
CBCentralManager:藍芽管理中心,做外部設備搜尋、連接。 CBPeripheral:外部設備 CBCharacteristic:外部設備的特徵。 首先先宣告: var centralManager: CBCentralManager = CBCentralManager.ini
儲存檔案: let savePanel = NSSavePanel() savePanel.canCreateDirectories = true savePanel.showsTagField = false savePanel.nameFieldStringValue = "localFile
用來操作 Core Data 的常數 private let coreDataContext = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 取的資料數量: func get
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { NSApplication.shared.terminate(self) return
字串交換: let str = "被誰喜歡,又喜歡誰呢?" // 交換 print(str.replacingOccurrences(of: ",又", with: "?")) //被誰喜歡?喜歡誰呢? 字串去首尾: let str = "被誰喜歡,又喜歡誰呢?" // 去首尾 print
int to data: //int to data var num = -12300 let data = Data.init(bytes: &num, count: MemoryLayout.size(ofValue: num)) // bytes : 8 elements //
CBCentralManager:藍芽管理中心,做外部設備搜尋、連接。 CBPeripheral:外部設備 CBCharacteristic:外部設備的特徵。 首先先宣告: var centralManager: CBCentralManager = CBCentralManager.ini
儲存檔案: let savePanel = NSSavePanel() savePanel.canCreateDirectories = true savePanel.showsTagField = false savePanel.nameFieldStringValue = "localFile
用來操作 Core Data 的常數 private let coreDataContext = (NSApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 取的資料數量: func get
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { NSApplication.shared.terminate(self) return
字串交換: let str = "被誰喜歡,又喜歡誰呢?" // 交換 print(str.replacingOccurrences(of: ",又", with: "?")) //被誰喜歡?喜歡誰呢? 字串去首尾: let str = "被誰喜歡,又喜歡誰呢?" // 去首尾 print
int to data: //int to data var num = -12300 let data = Data.init(bytes: &num, count: MemoryLayout.size(ofValue: num)) // bytes : 8 elements //
你可能也想看
Thumbnail
1.加權指數與櫃買指數 週五的加權指數在非農就業數據開出來後,雖稍微低於預期,但指數仍向上噴出,在美股開盤後於21500形成一個爆量假突破後急轉直下,就一路收至最低。 台股方面走勢需觀察週一在斷頭潮出現後,週二或週三開始有無買單進場支撐,在沒有明確的反轉訊號形成前,小夥伴盡量不要貿然抄底,或是追空
Thumbnail
重點摘要: 1.9 月降息 2 碼、進一步暗示年內還有 50 bp 降息 2.SEP 上修失業率預期,但快速的降息速率將有助失業率觸頂 3.未來幾個月經濟數據將繼續轉弱,經濟復甦的時點或是 1Q25 季底附近
Thumbnail
近期的「貼文發佈流程 & 版型大更新」功能大家使用了嗎? 新版式整體視覺上「更加凸顯圖片」,為了搭配這次的更新,我們推出首次貼文策展 ❤️ 使用貼文功能並完成這次的指定任務,還有機會獲得富士即可拍,讓你的美好回憶都可以用即可拍珍藏!
Thumbnail
字數算法 = string.count? 在swift算一個string的字數時候,很直覺的會想到用.count來算 let s = "這是幾個字呢".count print(s.count) // 6 毫無疑問的安心信賴6個字 表情符號的場合 let emoji = "😂" print
Thumbnail
一樣先來看官方文件 A view controller that provides access to documents or destinations outside your app’s sandbox. 其實就是讓你去讀取檔案App的東西 有兩種模式,Don’t copy the do
swift讀書筆記 https://docs.swift.org/swift-book/documentation/the-swift-programming-language/deinitialization/  class instance deallocated前會call deinitia
Thumbnail
swift讀書筆記 Documentation Edit descriptiondocs.swift.org objective-c 的init 會return value,swift 不會。 所有的property都必須在Init()裡面設定初始值,或設定stored property,這種
Thumbnail
Hahaha, I can't even say it with a straight face! / 哈哈哈!要得到我的原諒,等下輩子吧你!
三元條件運算子(Ternary Conditional Operator)是一種簡潔的寫法,用於在滿足條件時返回一個值,否則返回另一個值。 基本語法 其中,condition是要測試的條件,如果為true,則返回valueIfTrue,否則返回valueIfFalse。
Thumbnail
俄羅斯被踢出 SWIFT 支付系統,媒體形容是美、歐政府對俄羅斯發動了金融核戰。到底什麼是 SWIFT 它是如何運作的,鬼宿來告訴大家媒體沒有說清楚的事。可以這麼說:如果沒有 SWIFT;美元連在境內流動都將是不可能的任務。
本文推薦免費的3個網站,分為初學者、已有學過程式語言者兩類,鑑於PTT和自身的學習經驗,只要持之以恆的學習,Coding一定會給予回報。
Thumbnail
Taylor Swift 2014年的熱門曲"Shake It Off" 在youtube已累積28幾億的觀看次數,讓人朗朗上口的副歌前段,卻被指抄襲3LW 2001年的歌曲...
Thumbnail
1.加權指數與櫃買指數 週五的加權指數在非農就業數據開出來後,雖稍微低於預期,但指數仍向上噴出,在美股開盤後於21500形成一個爆量假突破後急轉直下,就一路收至最低。 台股方面走勢需觀察週一在斷頭潮出現後,週二或週三開始有無買單進場支撐,在沒有明確的反轉訊號形成前,小夥伴盡量不要貿然抄底,或是追空
Thumbnail
重點摘要: 1.9 月降息 2 碼、進一步暗示年內還有 50 bp 降息 2.SEP 上修失業率預期,但快速的降息速率將有助失業率觸頂 3.未來幾個月經濟數據將繼續轉弱,經濟復甦的時點或是 1Q25 季底附近
Thumbnail
近期的「貼文發佈流程 & 版型大更新」功能大家使用了嗎? 新版式整體視覺上「更加凸顯圖片」,為了搭配這次的更新,我們推出首次貼文策展 ❤️ 使用貼文功能並完成這次的指定任務,還有機會獲得富士即可拍,讓你的美好回憶都可以用即可拍珍藏!
Thumbnail
字數算法 = string.count? 在swift算一個string的字數時候,很直覺的會想到用.count來算 let s = "這是幾個字呢".count print(s.count) // 6 毫無疑問的安心信賴6個字 表情符號的場合 let emoji = "😂" print
Thumbnail
一樣先來看官方文件 A view controller that provides access to documents or destinations outside your app’s sandbox. 其實就是讓你去讀取檔案App的東西 有兩種模式,Don’t copy the do
swift讀書筆記 https://docs.swift.org/swift-book/documentation/the-swift-programming-language/deinitialization/  class instance deallocated前會call deinitia
Thumbnail
swift讀書筆記 Documentation Edit descriptiondocs.swift.org objective-c 的init 會return value,swift 不會。 所有的property都必須在Init()裡面設定初始值,或設定stored property,這種
Thumbnail
Hahaha, I can't even say it with a straight face! / 哈哈哈!要得到我的原諒,等下輩子吧你!
三元條件運算子(Ternary Conditional Operator)是一種簡潔的寫法,用於在滿足條件時返回一個值,否則返回另一個值。 基本語法 其中,condition是要測試的條件,如果為true,則返回valueIfTrue,否則返回valueIfFalse。
Thumbnail
俄羅斯被踢出 SWIFT 支付系統,媒體形容是美、歐政府對俄羅斯發動了金融核戰。到底什麼是 SWIFT 它是如何運作的,鬼宿來告訴大家媒體沒有說清楚的事。可以這麼說:如果沒有 SWIFT;美元連在境內流動都將是不可能的任務。
本文推薦免費的3個網站,分為初學者、已有學過程式語言者兩類,鑑於PTT和自身的學習經驗,只要持之以恆的學習,Coding一定會給予回報。
Thumbnail
Taylor Swift 2014年的熱門曲"Shake It Off" 在youtube已累積28幾億的觀看次數,讓人朗朗上口的副歌前段,卻被指抄襲3LW 2001年的歌曲...