ABLE
iOS 的 BLE 库。
这个轻量级的库是围绕 CoreBluetooth api 的包装器,增加了对闭包的支持,以便于处理所有 ble 操作。
此外,这个库还支持为所有 ble 操作指定自定义超时,这是 CoreBluetooth 默认不支持的功能。
此外,还提供了几个其他实用功能。
用法
您可以使用 CentralManager 或 PeripheralManager 对象来执行操作,就像您使用 CoreBluetooth 一样,因为大多数 API 与 CoreBluetooth 的 API 相似。
CentralManager
这是如何使用 CentralManager 来执行中央角色任务的示例
central = CentralManager(queue: DispatchQueue.main)
// Wait for powered on state to begin using the central, specifying the desired timeout. You can also set yourself as delegate to receive all state change notification if you need to.
central.waitForPoweredOn(withTimeout: 6.0) { (state) in
guard state == .poweredOn else {
return
}
self.central.scanForPeripherals(withServices: nil, timeoutInterval: 6.0) { result in
switch result {
case .success(let peripherals):
print("timeout reached: \(peripherals)")
// Connect to peripheral...
case .failure(let error):
print("scan error: \(error)")
// Handle error.
}
}
}
PeripheralManager
这是如何使用 PeripheralManager 来执行外围角色任务的示例
let peripheralManager = PeripheralManager(queue: DispatchQueue.main)
peripheralManager.waitForPoweredOn(withTimeout: 6.0) { (state) in
guard state == .poweredOn else {
return
}
let service = CBMutableService(type: CBUUID(string: "DE036077-4293-4768-B9EF-66429B46A3CB"), primary: true)
peripheralManager.add(service) { (result) in
switch result {
case .success(let service):
print("added service: \(service)")
// Start advertising.
peripheralManager.startAdvertising { (result) in
print("advertising result: \(result)")
}
case .failure(let error):
print("add service failure: \(error)")
}
}
}
安装
Carthage
如果您使用Carthage,您可以通过将其添加到Cartfile来依赖ABLE。
github "ale84/ABLE"
CocoaPods
请在Podfile中添加以下条目
pod 'ABLE'
测试
通过模拟主CoreBluetooth类实现对库的全面单元测试。
您可以使用库中提供的mocks来进行您的逻辑测试,或者如果您需要进一步自定义,可以编写自己的mocks。