在上一小节中,我们一起开发了基于蓝牙通讯的工具类,该类中详细的实现蓝牙连接流程中的每一个环节
本小节我们就以给小米手环发送数据使其震动来演示我们工具类的用法
工具类本身具有通用性,属于MVC中的
M层
,只负责处理自身负责的处理,不处理任何的业务逻辑和UI我的小米手环的identifer:60C955B2-8F7C……
- 后面我就不写了,每一个手环的唯一标识符都是不一样的
- 能够让小米手环震动的特征的UUID:2A06
能够让小米手环震动的数据:2(二进制数据)
示例效果:1。点击开始扫描按钮,搜索蓝牙设备,并且将外设的信息显示在tableview中 2.点击指定的tableviewcell,让小米手环震动
#import "ViewController.h" #import "HMBluetoothManager.h" @interface ViewController ()<UITableViewDataSource,UITableViewDelegate> @property (weak, nonatomic) IBOutlet UITableView *tableView; @end //我的小米手环dentifier #define kIdentifier @"60C955B2-8F7C-8784-665F-D05E520F5A12" @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } #pragma mark -扫描按钮 - (IBAction)scanButtonClick:(id)sender { kHMBluetoothManager.UUID = @"2A06"; //1.开始扫描 [kHMBluetoothManager BeginScanPeripheral:^(CBPeripheral *peripheral) { //刷新tableview [self.tableView reloadData]; }]; } #pragma mark -tableviewdelegate - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return kHMBluetoothManager.scanArr.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath]; CBPeripheral *peripheral = kHMBluetoothManager.scanArr[indexPath.row]; cell.textLabel.text = [peripheral.identifier UUIDString]; cell.detailTextLabel.text = peripheral.name; return cell; } //点击cell连接设备 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //获取点击的外设 CBPeripheral *peripheral = kHMBluetoothManager.scanArr[indexPath.row]; //判断是否是我的小米手环(专门为了测试买的),因为蓝牙会扫描到周边很多外设,我们通过唯一标识符来判断自己的外设 if ([[peripheral.identifier UUIDString] isEqualToString:kIdentifier]) { //3.连接设备 [kHMBluetoothManager connectPeripheral:peripheral Completion:^(CBPeripheral *peripheral, NSString *connectState) { NSLog(@"%@",connectState); //4.发送数据 //实际开发中,扫描特征会有一定的延迟,我们可以通过回调或者通知来获取发现特征的回调,这里为了快速演示,我就设置了3s的延迟 dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{ Byte *byte[1]; byte[0]= 02 & 0xff; NSData *data = [NSData dataWithBytes:byte length:1]; [kHMBluetoothManager writeValue:data toPeripheral:kHMBluetoothManager.currentPeripheral characteristic:kHMBluetoothManager.currentCharacteristic]; }); }]; } else { NSLog(@"这不是你的小米手环"); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end