美文网首页
Swift(OC) 蓝牙4.0(获取蓝牙设备Mac地址)

Swift(OC) 蓝牙4.0(获取蓝牙设备Mac地址)

作者: 70b7461fcbcb | 来源:发表于2017-10-31 17:19 被阅读251次

    话不多说,直接上代码

    OC版本

    服务选择180A,特征选择2A23然后连接

    
    /**
    
    * 接收数据
    
    */
    
    - (void)peripheral:(CBPeripheral *)peripheral didUpdateValueForCharacteristic:(CBCharacteristic *)characteristic error:(NSError *)error{
    
    if([characteristic.UUID isEqual:[CBUUID UUIDWithString:@"2A23"]])
    
    {
    
    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(@"MAC地址是macString:%@",macString);
    
    }
    
    }
    
    

    Swift版

    服务选择Device Information,特征选择System ID然后连接

    
    //接受数据
    
    public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?)
    
    {
    
    if "\(characteristic.uuid)" == "System ID"{
    
    var strarr = String()
    
    for readData in characteristic.value! {
    
    strarr += String(format: "%x",readData)
    
    }
    
    let string:NSString = strarr as NSString
    
    var str = string.substring(with: NSMakeRange(12,2)).uppercased()
    
    str = str + ":"
    
    str = str + string.substring(with: NSMakeRange(10,2)).uppercased()
    
    str = str + ":"
    
    str = str + string.substring(with: NSMakeRange(8,2)).uppercased()
    
    str = str + ":"
    
    str = str + string.substring(with: NSMakeRange(4,2)).uppercased()
    
    str = str + ":"
    
    str = str + string.substring(with: NSMakeRange(2,2)).uppercased()
    
    str = str + ":"
    
    str = str + string.substring(with: NSMakeRange(0,2)).uppercased()
    
    print("Mac地址:" + str)
    
    }
    
    }
    
    

    相关文章

      网友评论

          本文标题:Swift(OC) 蓝牙4.0(获取蓝牙设备Mac地址)

          本文链接:https://www.haomeiwen.com/subject/arnbpxtx.html