#import "ViewController.h"
#import <CoreBluetooth/CoreBluetooth.h>
@interface ViewController () <CBCentralManagerDelegate, CBPeripheralDelegate>
@property (nonatomic, strong) CBCentralManager *centralManager;
@property (nonatomic, strong) CBPeripheral *peripheral;
@property (nonatomic, strong) CBCharacteristic *characteristic;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 初始化中心设备
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}
- (IBAction)printButtonPressed:(id)sender {
// 扫描并连接到外围设备
[self.centralManager scanForPeripheralsWithServices:nil options:nil];
}
- (IBAction)sendButtonPressed:(id)sender {
// 将输入框中的信息转换为蓝牙广播并发送出去
NSString *message = self.textField.text;
NSData *data = [message dataUsingEncoding:NSUTF8StringEncoding];
[self.peripheral writeValue:data forCharacteristic:self.characteristic type:CBCharacteristicWriteWithResponse];
}
#pragma mark - CBCentralManagerDelegate
- (void)centralManagerDidUpdateState:(CBCentralManager *)central {
if (central.state == CBManagerStatePoweredOn) {
// 中心设备已准备好
} else {
// 中心设备不可用
}
}
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary<NSString *,id> *)advertisementData RSSI:(NSNumber *)RSSI {
// 找到外围设备后,连接到它
if ([peripheral.name isEqualToString:@"YourPeripheralName"]) {
self.peripheral = peripheral;
[self.centralManager connectPeripheral:peripheral options:nil];
}
}
- (void)centralManager:(CBCentralManager *)central didConnectPeripheral:(CBPeripheral *)peripheral {
// 连接成功后,开始发现外围设备的服务和特征值
peripheral.delegate = self;
[peripheral discoverServices:nil];
}
#pragma mark - CBPeripheralDelegate
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error {
if (error) {
// 发现服务时发生错误
return;
}
// 遍历外围设备的服务
for (CBService *service in peripheral.services) {
[peripheral discoverCharacteristics:nil forService:service];
}
}
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
// 发现特征值时发生错误
return;
}
// 遍历服务的特征值
for (CBCharacteristic *characteristic in service.characteristics) {
// 订阅特征值以接收蓝牙广播
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
// 保存特征值以便发送蓝牙广播
self.characteristic = characteristic;
}
}
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
if (error) {
// 接收蓝牙广播时发生错误
return;
}
// 将接收到的蓝牙广播打印出来
NSData *data = characteristic.value;
NSString *message = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", message);
}
@end