1. 定义常量
NSString * const HeartRateServiceUUIDString = @"180D";
NSString * const HeartRateCharacteristicUUIDStringNoti = @"2A37";
NSString * const RealTimeHeartRateNotifaction = @"RealTimeHeartRateNotifaction";
2.在扫描到的外设中找心率服务
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"查找服务失败");
}
//find HR service
if ([service.UUID.UUIDString isEqualToString: HeartRateServiceUUIDString]) {
for (CBCharacteristic *characteristic in service.characteristics) {
if ([characteristic.UUID.UUIDString isEqualToString: HeartRateCharacteristicUUIDStringNoti]) {
[peripheral setNotifyValue:YES forCharacteristic:characteristic];
self.characteristicHR = characteristic;
}
}
}
}
3.在外设收到通知回调代理方法里面获取心率值
- (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error {
[self removeTimer];
if ([characteristic.UUID.UUIDString isEqualToString: HeartRateCharacteristicUUIDStringNoti]) {
Byte *bytes = (Byte *)characteristic.value.bytes;
int hr = bytes[1];
//post notification update UI
[[NSNotificationCenter defaultCenter] postNotificationName: RealTimeHeartRateNotifaction object:nil userInfo:@{@"realTimeHR":@(hr)}];
return;
}
}
4.监听通知,更新UI
[[NSNotificationCenterdefaultCenter] addObserver:selfselector:@selector(realTimeHR:) name:APPSRealTimeHRNotiobject:nil];
//updateHR
- (void)realTimeHR:(NSNotification *)nofi{
Log(@"%@",nofi.userInfo);
int hr = [nofi.userInfo[@"realTimeHR"] intValue];
[heartRateCircle setProgress:hr*1.0/180 animated:YES];
lblheartRate2.text=[NSString stringWithFormat:@"%d",hr];
}