SwiftBluetooth

通过现代异步 Swift API,轻松地在新的或现有的项目中与蓝牙外设交互。

特性

示例

API 文档。

完整示例

异步 API 使整个蓝牙生命周期更加简单,使用您已经熟悉的 CoreBluetooth 中的方法名称。

import SwiftBluetooth

let central = CentralManager()
try await central.waitUntilReady()

// Find and connect to the first available peripheral
let peripheral = await central.scanForPeripherals(withServices: [myService]).first!
try await central.connect(peripheral, timeout: connectionTimeout)

// Discover services and characteristics
let service = try await peripheral.discoverServices([myService]).first!
let _ = try await peripheral.discoverCharacteristics([.someCharacteristic], for: service)

// Read data directly from your characteristic
let value = try await peripheral.readValue(for: .someCharacteristic)

central.cancelPeripheralConnection(peripheral)

回调

现在,标准的 CoreBluetooth 方法也有一个额外的重载,它接受 completionHandler,适用于未使用 Swift 并发的项目。

central.connect(peripheral) { result in
  if result == .failure(let error) {
    // Issue connecting
    return
  }

  // Connected!
}

现在,方法通常有 3 个重载。一个标记为 async,一个带有 completionHandler,以及原始的 CoreBluetooth 版本。这意味着您可以选择当时最方便的一个。

流式传输发现的外设

某些操作(如扫描)符合 AsyncStream,这意味着您可以使用 for-await-in 循环来迭代新项目。

for await peripheral in await central.scanForPeripherals() {
  print("Discovered:", peripheral.name ?? "Unknown")
}

定义特征

特征可以在标准的 Characteristic 类型上进行静态定义,从而消除了在您的应用程序中跟踪 CBCharacteristic 实例的负担。

extension Characteristic {
  static let someCharacteristic = Self("00000000-0000-0000-0000-000000000000")
}

// Use those characteristics later on your peripheral
try await myPeripheral.readValue(for: .someCharacteristic)

使用回调进行监听

持久性任务返回一个 CancellableTask,当您完成时需要取消它。

let task = central.scanForPeripherals { peripheral in
  print("Discovered:", peripheral.name ?? "Unknown")
}

// At some point later, cancel the task to stop scanning
task.cancel()

注意 调用 central.stopScan() 也会取消任何外设扫描任务

迁移现有项目

已经使用 CoreBluetooth 的现有项目可以通过对标准类型进行类型别名立即开始使用。之后,您可以按照自己的进度采用异步 API。

import CoreBluetooth
import SwiftBluetooth // Add this

// Override existing CoreBluetooth classes to use SwiftBluetooth
typealias CBCentralManager         = SwiftBluetooth.CentralManager
typealias CBCentralManagerDelegate = SwiftBluetooth.CentralManagerDelegate
typealias CBPeripheral             = SwiftBluetooth.Peripheral
typealias CBPeripheralDelegate     = SwiftBluetooth.PeripheralDelegate

// Your existing code should continue to work as normal.
// But now you have access to all the new API's!

安装

Xcode

“Swift Package Manager”选项卡中添加 https://github.com/exPHAT/SwiftBluetooth.git

Swift Package Manager

在您的 Package.swift 文件中添加 SwiftBluetooth 作为依赖项

let package = Package(
  ...
  dependencies: [
    // Add the package to your dependencies
    .package(url: "https://github.com/exPHAT/SwiftBluetooth.git", branch: "master"),
  ],
  ...
  targets: [
    // Add SwiftBluetooth as a dependency on any target you want to use it in
    .target(name: "MyTarget",
            dependencies: [.byName(name: "SwiftBluetooth")])
  ]
  ...
)