SkyBlue
示例
要运行示例项目,请先从仓库中克隆,然后在 Example 目录中首先运行 pod install
要求
操作系统 >= iOS 8.0
安装
SkyBlue 可通过 CocoaPods 获取。要安装,只需在 Podfile 中添加以下行
pod 'SkyBlue'
如何使用
- 获取单个实例
self.bleManager = [BLEManager sharedInstance];
// Set scan timeout to 10 sec, only available when `continousScan` = NO
self.bleManager.scanInterval = 10;
// Scan will not terminate until user invoke `stopScan`
self.bleManager.continousScan = YES;
// Set connect timeout to 10 sec
self.bleManager.connectTimeout = 10;
// Set enumeration timeout to 10 sec
self.bleManager.enumerateTimeout = 10;
// Set write characteristic value timeout to 10 sec
self.bleManager.sendDataTimeout = 10;
- 扫描
[_bleManager scanPeripheralWithUUIDs:uuids resultCallback:^(NSDictionary<NSUUID *, BLEPeripheral *> *devices, NSError *error) {
NSMutableArray *devs = [NSMutableArray array];
[devices enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
NSLog(@"Device UUID: @%", key);
BLEPeripheral *device = obj;
// Do anything you need with BLEPeripheral
}];
}];
- 连接
[_bleManager connectPeripheral:peripheral completion:^(NSNumber *success, NSError *error) {
if (error) {
NSLog(@"Failed to connect BLE Peripheral");
} else {
// Connected
Do everything you need after connected
}
}];
- 您可以通过
connectedPeripherals
访问已连接的设备,这是一个 NSDictionary,用于保存已连接的外设。键是外设的 UUID。
_bleManager.connectedPeripherals
- 订阅/取消订阅
// Subscribe
[_bleManager subscribeNotificationForPeripheral:peripheral
characteristicUUID:BLE_CHARACTERISTIC_UUID // Characteristic UUID String, eg. FFE1
resultCallback:^(NSData *data, NSError *error) {
if (error) {
NSLog(@"Error: %@", error.localizedDescription);
} else {
// Processing `data` as you want
}
}];
// Unsubscribe
[_bleManager unsubscribeNotificationForPeripheral:peripheral
forCharacteristic:characteristic];
- 读取
[_bleManager readPeripheral:peripheral withCharacteristic:characteristic completion:^(NSData *data, NSError *error) {
// Error is not null if read fail
}];
- 写入
[_bleManager sendData:data
toPeripheral:peripheral
characteristicUUID:characteristicUUID
completion:^(NSNumber *success, NSError *error) {
// error indicate the write operation is success or not
}];
- 断开连接
[_bleManager disconnectPeripheral:peripheral
completion:^(NSNumber *success, NSError *error) {
// Indicate disconnect or not
};
- 通知
/// Disconnect notification
extern NSString *BLENotificationDisconnected;
/// Scan stop notification
extern NSString *BLENotificationScanStopped;
变更日志
v0.5.0
- 在发现服务时不要指定服务uuid
v0.4.0
- 移除缺失间隔属性
- 移除缺失检查逻辑
- 将扫描回调回函数修改为每次返回一个外围设备
v0.3.0
- 向BLEPeripheral类添加广告数据字段,这有助于开发者访问从外围设备接收到的最新广告数据。
v0.2.1
- 修复连接回调在外围设备状态改变之前调用的问题。
v0.2.0
- 从BLEManager移除NSAssert
- 支持同时创建到不同外围设备的多个连接。
- 添加写入操作计时器来检测写入值超时
作者
enix223, [email protected]
许可协议
SkyBlue托管于MIT许可协议下。有关更多信息,请参阅LICENSE文件。