Swiftui - 蓝牙低功耗状态始终未知

Posted

技术标签:

【中文标题】Swiftui - 蓝牙低功耗状态始终未知【英文标题】:Swiftui - Bluetooth Low Energy status is always unknown 【发布时间】:2020-05-01 20:32:56 【问题描述】:

我有一个使用 BLE 的 swiftui 程序。但是当我想知道 centralManager (我的 iPhone) 的状态时,它会显示未知。我不知道是我的代码有错误还是我的手机有问题。

我的内容视图:

import SwiftUI
import CoreBluetooth

struct ContentView: View 
    var body: some View 
        VStack 
            Text("View").background(Color.init(red: 56, green: 22, blue: 22))
        
        .onAppear(perform: connectBLEDevice)
    
    private func connectBLEDevice()
        print("connectBLEDevice")
        let ble = BLEConnection()
        ble.startCentralManager()
    

我的 BLE 课程:

import CoreBluetooth

class BLEConnection: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate 
    var centralManager: CBCentralManager!
    var myPeripheral: CBPeripheral!

func startCentralManager() 
    self.centralManager = CBCentralManager(delegate: self, queue: nil)
    print("Central Manager State: \(self.centralManager.state)")
    centralManagerDidUpdateState(self.centralManager)


func centralManagerDidUpdateState(_ central: CBCentralManager) 
    switch (central.state) 
       case .unsupported:
        print("BLE is Unsupported")
        break
       case .unauthorized:
        print("BLE is Unauthorized")
        break
       case .unknown:
        print("BLE is Unknown")
        break
       case .resetting:
        print("BLE is Resetting")
        break
       case .poweredOff:
        print("BLE is Powered Off")
        break
       case .poweredOn:
        print("BLE powered on")
        break
    @unknown default:
        break
    


【问题讨论】:

使用 SwiftUI,您确实应该将长期存在的对象(例如蓝牙类)移动到环境中。你现在的样子,connectBLEDevice一回来就放出来 另外,你不要自己调用委托方法;当状态发生变化时,系统会调用委托方法 【参考方案1】:

这里有一些修复

struct ContentView: View 
    private let ble = BLEConnection() // make member !!

    var body: some View 
        VStack 
            Text("View").background(Color.init(red: 56, green: 22, blue: 22))
        
        .onAppear(perform: connectBLEDevice)
    

    private func connectBLEDevice()
        print("connectBLEDevice")
        ble.startCentralManager()
    

Delegate 将被 BLE 引擎异步调用,所以不要强行调用它 - 只需为每个状态添加处理代码

func startCentralManager() 
    self.centralManager = CBCentralManager(delegate: self, queue: nil)

//    print("Central Manager State: \(self.centralManager.state)") //
//    centralManagerDidUpdateState(self.centralManager)  // << wrong !!


【讨论】:

以上是关于Swiftui - 蓝牙低功耗状态始终未知的主要内容,如果未能解决你的问题,请参考以下文章

总结:低功耗蓝牙常见的4种工作模式

Uni-App开发BLE低功耗蓝牙流程

Android ble (蓝牙低功耗) 中的坑和技巧

Android 低功耗蓝牙(Ble) 开发总结

Android 低功耗Ble 蓝牙4.0多连接 开源框架

低功耗蓝牙Ble的详细使用流程