当前位置:   article > 正文

iOS之获取蓝牙Mac地址_ios蓝牙device id转mac

ios蓝牙device id转mac

在做iOS蓝牙开发的时候肯定会遇到这种问题,苹果自带的CoreBluetooth SDK中不能获取到蓝牙的Mac地址,只能得到UUID,但是UUID并不是唯一的,换一个设备再连接UUID就不一样了。而且Android手机是可以获取到Mac地址的,不能很好的兼容Android手机,Android是不可能获取到UUID,为了很好的兼容,只能iOS想办法获取Mac地址了。幸运的是iOS也不是没有办法获取到Mac地址。
主要思路

虽然苹果官方的API没有获取Mac地址的方法,但是当我翻看蓝牙的文档的时候,我发现蓝牙有提供一个设备信息的service[service UUID:0x180A],里面提供了两个characteristic:获取芯片的Mac地址(0x2A23 )和获取软件的版本号(0x2A26)。如下图所示:


实现

  1. - (void)getMacAddress:(MPPeripheral *)mPeripheral
  2. {
  3. CBUUID *macServiceUUID = [CBUUID UUIDWithString:@"180A"];
  4. CBUUID *macCharcteristicUUID = [CBUUID UUIDWithString:@"2A23"];
  5. [mPeripheral discoverServices:@[macServiceUUID] withBlock:^(MPPeripheral *peripheral, NSError *error) {
  6. if(peripheral.services.count){
  7. MPService *service = [peripheral.services objectAtIndex:0];
  8. [service discoverCharacteristics:@[macCharcteristicUUID] withBlock:^(MPPeripheral *peripheral, MPService *service, NSError *error) {
  9. for(MPCharacteristic *characteristic in service.characteristics){
  10. if([characteristic.UUID isEqual:macCharcteristicUUID]){
  11. [characteristic readValueWithBlock:^(MPPeripheral *peripheral, MPCharacteristic *characteristic, NSError *error){
  12. NSString *value = [NSString stringWithFormat:@"%@",characteristic.value];
  13. NSMutableString *macString = [[NSMutableString alloc] init];
  14. [macString appendString:[[value substringWithRange:NSMakeRange(16, 2)] uppercaseString]];
  15. [macString appendString:@":"];
  16. [macString appendString:[[value substringWithRange:NSMakeRange(14, 2)] uppercaseString]];
  17. [macString appendString:@":"];
  18. [macString appendString:[[value substringWithRange:NSMakeRange(12, 2)] uppercaseString]];
  19. [macString appendString:@":"];
  20. [macString appendString:[[value substringWithRange:NSMakeRange(5, 2)] uppercaseString]];
  21. [macString appendString:@":"];
  22. [macString appendString:[[value substringWithRange:NSMakeRange(3, 2)] uppercaseString]];
  23. [macString appendString:@":"];
  24. [macString appendString:[[value substringWithRange:NSMakeRange(1, 2)] uppercaseString]];
  25. NSLog(@"macString:%@",macString);
  26. }];
  27. }
  28. }
  29. }];
  30. }
  31. }];
  32. }

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/不正经/article/detail/428249
推荐阅读
相关标签
  

闽ICP备14008679号