1. 定義常量
NSString * const HeartRateServiceUUIDString = @"180D";
NSString * const HeartRateCharacteristicUUIDStringNoti = @"2A37";
NSString * const RealTimeHeartRateNotifaction = @"RealTimeHeartRateNotifaction";
2.在掃描到的外設(shè)中找心率服務(wù)
- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error {
if (error) {
NSLog(@"查找服務(wù)失敗");
}
//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.在外設(shè)收到通知回調(diào)代理方法里面獲取心率值
- (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.監(jiān)聽通知,更新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];
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者