我目前正在使用CoreBluetooth进行开发,并且设法获得RSSI强度。我可以在控制台中打印它,但是当我想在IBAction中使用它时,它将无法工作。我猜是因为RSSI var不是局部变量。
这是我从中获得RSSI强度的方法:
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? String
let rssi = RSSI // The const that stores the RSSI-data
print(rssi)
if device?.contains(BLE_NAME) == true {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
manager.connect(peripheral, options: nil)
}
}
这是我希望rssi const位于的IBAction:
@IBAction func btnPressed(_ sender: Any) {
rssiLbl.text = "\(rssi)"
}
但是,我不知道该如何做。我敢打赌,对于大多数人来说,这是一个非常基本的问题,但是我无法使其正常工作。
最佳答案
正如其他人所说。将rssi声明为类级变量:
private var rssi: NSNumber?
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
let device = (advertisementData as NSDictionary).object(forKey: CBAdvertisementDataLocalNameKey) as? String
self.rssi = RSSI
print(self.rssi)
if device?.contains(BLE_NAME) == true {
self.manager.stopScan()
self.peripheral = peripheral
self.peripheral.delegate = self
manager.connect(peripheral, options: nil)
}
}
@IBAction func btnPressed(_ sender: Any) {
if let rssi = self.rssi {
rssiLbl.text = "\(rssi)"
} else {
rssiLbl.text = "Undetermined"
}
关于ios - 用另一种方法访问let/var Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42941019/