美文网首页
swift CoreBluetooth使用

swift CoreBluetooth使用

作者: Lucky_1122 | 来源:发表于2024-08-18 18:41 被阅读0次

iOS中使用CBCentralManager实现蓝牙传输数据
关键步骤如下

  1. 创建中央管理器 (CBCentralManager)
    初始化: 在你的 ViewController 中创建并初始化 CBCentralManager 实例,并实现CBCentralManagerDelegate代理方法。
    设置代理: 实现并设置 CBCentralManagerDelegate 代理,以便处理蓝牙状态变化、设备发现、连接、断开连接等事件。
centralManager = CBCentralManager(delegate: self, queue: nil)

  1. 扫描外围设备
    状态监控: 在 centralManagerDidUpdateState 方法中处理蓝牙状态(如是否开启),并根据状态决定是否开始扫描设备。
 func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            print("Bluetooth is On")
            // 开始扫描
            centralManager?.scanForPeripherals(withServices: nil, options: nil)
        case .poweredOff:
            print("Bluetooth is Off")
        default:
            print("Bluetooth status changed to: \(central.state.rawValue)")
        }
    }

3.扫描到外部设备、停止扫描、链接设备
处理发现的设备: 在 didDiscover 方法中处理扫描到的设备。你可以显示设备列表或者直接连接某个设备。为了避免重复连接,可以在发现目标设备后停止扫描。

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    centralManager.stopScan()
    discoveredPeripheral = peripheral
    centralManager.connect(peripheral, options: nil)
}

处理连接成功: 在 didConnect 方法中处理成功连接事件,通常需要设置外围设备的代理,并开始发现服务。

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    peripheral.delegate = self
    peripheral.discoverServices(nil)
}

  1. 发现服务和特征
    发现服务: 使用 discoverServices 方法发现外围设备上的服务。在 didDiscoverServices 方法中处理发现的服务。
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    for service in peripheral.services ?? [] {
        peripheral.discoverCharacteristics(nil, for: service)
    }
}

发现特征: 使用 discoverCharacteristics 方法发现每个服务中的特征。在 didDiscoverCharacteristics 方法中处理发现的特征。

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    for characteristic in service.characteristics ?? [] {
        // 如果是你想要的特征,保存它
        if characteristic.properties.contains(.write) {
            targetCharacteristic = characteristic
        }
    }
}

  1. 传输数据
    发送数据: 在需要时,比如用户点击按钮时,使用 writeValue 方法将数据发送到特定的特征。
func sendTime() {
    let currentTimeString = DateFormatter.localizedString(from: Date(), dateStyle: .short, timeStyle: .long)
    let dataToSend = currentTimeString.data(using: .utf8)!
    peripheral.writeValue(dataToSend, for: targetCharacteristic!, type: .withResponse)
}

接收数据: 如果设备返回数据,在 didUpdateValueFor 方法中处理接收到的数据

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if let data = characteristic.value {
        print("Received data: \(String(data: data, encoding: .utf8)!)")
    }
}

  1. 断开连接
    主动断开连接: 如果需要,你可以使用 cancelPeripheralConnection 方法主动断开与外围设备的连接。
centralManager.cancelPeripheralConnection(peripheral)

处理断开事件: 在 didDisconnectPeripheral 方法中处理断开连接事件,你可以选择重新扫描设备或者提示用户连接已断开。

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    print("Disconnected from \(peripheral.name ?? "Unknown")")
    centralManager.scanForPeripherals(withServices: nil, options: nil)
}

  1. 清理资源
    停止扫描: 在适当时机停止扫描,防止耗电。
    释放资源: 在视图消失时(如 viewWillDisappear)清理或断开连接,释放不必要的资源。
override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    centralManager.stopScan()
    if let peripheral = discoveredPeripheral {
        centralManager.cancelPeripheralConnection(peripheral)
    }
}

相关文章

网友评论

      本文标题:swift CoreBluetooth使用

      本文链接:https://www.haomeiwen.com/subject/uiwpkjtx.html