我在Objective-C中有一个旧项目。我需要在最新的Swift-5中进行转换。 除了Eddystone信标检测之外,其他一切都正常。
旧的Objective C代码
-(NSString *) findNameSpace : (id) beaconInfo {
ESSBeaconInfo *beacon = beaconInfo;
ESSBeaconID *Bid = beacon.beaconID;
NSLog(@"Beacon : %@", beacon);
NSLog(@"Beacon ID Length : %lu",(unsigned long)Bid.beaconID.length);
if (Bid.beaconID.length == 16) {
NSData *d1 = [Bid.beaconID subdataWithRange:NSMakeRange(0, 10)];
NSLog(@"Sub Data : %@", d1);
NSString *namespace = [[NSString stringWithFormat:@"%@",d1] stringByReplacingOccurrencesOfString:@"<" withString:@""];
namespace = [namespace stringByReplacingOccurrencesOfString:@">" withString:@""];
namespace = [namespace stringByReplacingOccurrencesOfString:@" " withString:@""];
NSLog(@"namespace : %@", namespace);
return namespace;
}
return @"";
}
输出:-
Beacon:Eddystone,id:ESSBeaconID:beaconID = ,RSSI:-65,txPower:-31
信标ID长度:16
命名空间:a457ae5727fa30f48dc9
我的Swift代码
func findNameSpace(_ beaconInfo: Any) -> String? {
let beacon: ESSBeaconInfo = beaconInfo as! ESSBeaconInfo
let Bid: ESSBeaconID = beacon.beaconID
print("Beacon : \(beacon)")
print("Beacon ID Length : \(Bid.beaconID.count)")
if Bid.beaconID.count == 16 {
let d1 = Bid.beaconID.subdata(in: Range(NSRange(location: 0, length: 10))!)
print("Sub Data : \(d1)")
var namespace: String? = nil
namespace = "\(d1)".replacingOccurrences(of: "<", with: "")
namespace = namespace?.replacingOccurrences(of: ">", with: "")
namespace = namespace?.replacingOccurrences(of: " ", with: "")
print("namespace : \(namespace ?? "")")
return namespace
}
return ""
}
输出:-
Beacon:Eddystone,id:ESSBeaconID:beaconID = ,RSSI:-51,txPower:-31
信标ID长度:16
子数据:10个字节
命名空间:10个字节
======================================
我在获取名称空间时遇到问题。因为您可以从上面的输出中看到。数据正在我的Swift代码中以字节为单位转换。我不知道如何处理。 目标C代码运行正常。 任何帮助表示赞赏!谢谢。
答案 0 :(得分:0)
这是解决方案,适用于我的情况。
在此处发布答案,以帮助可能面临同样问题的人们。希望对某人有帮助!
func findNameSpace(_ beaconInfo: Any) -> String? {
let beacon: ESSBeaconInfo = beaconInfo as! ESSBeaconInfo
let Bid: ESSBeaconID = beacon.beaconID
print("Beacon : \(beacon)")
print("Beacon ID Length : \(Bid.beaconID.count)")
if Bid.beaconID.count == 16 {
let d1 = Bid.beaconID.subdata(in: Range(NSRange(location: 0, length: 10))!)
print("Sub Data : \(d1)")
var namespace: String? = nil
namespace = "\(d1.hexEncodedString())".replacingOccurrences(of: "<", with: "")
namespace = namespace?.replacingOccurrences(of: ">", with: "")
namespace = namespace?.replacingOccurrences(of: " ", with: "")
print("namespace : \(namespace ?? "")")
return namespace
}
return ""
}
func hexEncodedString(options: HexEncodingOptions = []) -> String {
let format = options.contains(.upperCase) ? "%02hhX" : "%02hhx"
return map { String(format: format, $0) }.joined()
}