赞
踩
在做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)。如下图所示:
实现
- - (void)getMacAddress:(MPPeripheral *)mPeripheral
- {
- CBUUID *macServiceUUID = [CBUUID UUIDWithString:@"180A"];
- CBUUID *macCharcteristicUUID = [CBUUID UUIDWithString:@"2A23"];
- [mPeripheral discoverServices:@[macServiceUUID] withBlock:^(MPPeripheral *peripheral, NSError *error) {
- if(peripheral.services.count){
- MPService *service = [peripheral.services objectAtIndex:0];
- [service discoverCharacteristics:@[macCharcteristicUUID] withBlock:^(MPPeripheral *peripheral, MPService *service, NSError *error) {
- for(MPCharacteristic *characteristic in service.characteristics){
- if([characteristic.UUID isEqual:macCharcteristicUUID]){
- [characteristic readValueWithBlock:^(MPPeripheral *peripheral, MPCharacteristic *characteristic, NSError *error){
- NSString *value = [NSString stringWithFormat:@"%@",characteristic.value];
- NSMutableString *macString = [[NSMutableString alloc] init];
- [macString appendString:[[value substringWithRange:NSMakeRange(16, 2)] uppercaseString]];
- [macString appendString:@":"];
- [macString appendString:[[value substringWithRange:NSMakeRange(14, 2)] uppercaseString]];
- [macString appendString:@":"];
- [macString appendString:[[value substringWithRange:NSMakeRange(12, 2)] uppercaseString]];
- [macString appendString:@":"];
- [macString appendString:[[value substringWithRange:NSMakeRange(5, 2)] uppercaseString]];
- [macString appendString:@":"];
- [macString appendString:[[value substringWithRange:NSMakeRange(3, 2)] uppercaseString]];
- [macString appendString:@":"];
- [macString appendString:[[value substringWithRange:NSMakeRange(1, 2)] uppercaseString]];
- NSLog(@"macString:%@",macString);
- }];
- }
- }
-
- }];
- }
- }];
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。