根据Swift 2.0文档 for CLBeaconRegion,仍然可以将peripheralDataWithMeasuredPower:方法的输出传递给CLPeripheralManager的startAdvertising:方法。
获取信标广告数据
- peripheralDataWithMeasuredPower:检索可用于将当前设备宣传为信标的数据。 声明 SWIFTfunc peripheralDataWithMeasuredPower(_measuredPower: NSNumber?) -> NSMutableDictionary目标-C- (NSMutableDictionary<NSString *,id> * _Nonnull)peripheralDataWithMeasuredPower:(NSNumber * _Nullable)measuredPower参数measuredPower设备的接收信号强度指示器(RSSI)值(以分贝为单位)。此值表示距离一米远的信标的测量强度,并在测距期间使用。指定nil以使用设备的默认值。 返回值 可以与CBPeripheralManager一起使用的数据字典,用于将当前设备宣传为信标。 讨论 返回的字典编码信标的识别信息以及宣传信标所需的其他信息。您不应该需要直接访问字典内容。将字典传递给startAdvertising:的CBPeripheralManager方法,以便开始对信标进行广告宣传。 Availability 可在iOS 7.0及更高版本中获得。
然而,peripheralDataWithMeasuredPower:返回一个NSMutableDictionary,而CLPeripheralManager的startAdvertising:方法则接受Swift [String : AnyObject]?字典,尽管文档声称它接受NSDictionary。在SWIFT1.0中工作的下列代码:
// Set up a beacon region with the UUID, Major and Minor values
let region = CLBeaconRegion(proximityUUID:beaconUUID!, major:withMajor.unsignedShortValue, minor:withMinor.unsignedShortValue, identifier:"com.example.beacon")
// Attempt to set up a peripheral with the measured power
let peripheralData = region.peripheralDataWithMeasuredPower(withPower)
_peripheralManager!.startAdvertising(peripheralData)在SWIFT2.0中,相同的代码无法使用警告进行编译:编译失败,并发出警告:
NSDictionary不能转换为[String : AnyObject];您是否有意使用as!强制下压?
然而,强迫沮丧总是失败的。
这是一个文档错误,SWIFT2.0中的一个bug,还是我遗漏了什么?
发布于 2015-10-06 14:18:30
问题似乎是,NSMutableDictionary很难转换成Swift的Dictionary,但NSDictinoary是。因此,我最终首先将NSMutableDictionary转换为NSDictinoary:
let pd = NSDictionary(dictionary: region.peripheralDataWithMeasuredPower(nil))
as! [String: AnyObject]
peripheralManager.startAdvertising(pd)而且起作用了!
https://stackoverflow.com/questions/32834219
复制相似问题