我是 swift 的初学者,尝试开发显示 BLE 特性的简单程序。我通过打印确认我捕获了目标特征的 UUID
myCharacteristicUUID_1 : (
"Manufacturer Name String",
"Model Number String",
"Serial Number String",
"Hardware Revision String",
"Firmware Revision String",
"Software Revision String"
)
但是,在 override func prepare(for segue: UIStoryboardSegue, sender: Any?), 我再次通过打印检查,发现数据消失了,如下所示;
myCharacteristicUUID_2 : (
)
我可以移交其他类型的值(例如字符串、文本等),但我无法处理从 BLE 捕获的数据。有人能指出当我在 segue 中使用来自 BLE 的数据时我必须做什么吗? 下面是我的代码;
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor targetService: CBService, error: Error?) {
if error != nil {
print("Characteristic NOT found : \(error)")
}
let foundCharacteristics = targetService.characteristics
for c in foundCharacteristics! as [CBCharacteristic] {
myCharacteristicUUID.add(c.uuid)
}
print("myCharacteristicUUID_1 : \(myCharacteristicUUID)")
}
// prepare for segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "mySegue") {
print("myCharacteristicUUID_2 : \(myCharacteristicUUID)")
let mySecondViewController : SecondViewController = segue.destination as! SecondViewController
mySecondViewController.relayedFoundCharacteristicUUID = myCharacteristicUUID
}
}
最佳答案
这就是 myCharacterisitcUUID
未正确读取的原因。请查看performSegue
的位置。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedService = myService[indexPath.row] as! CBService
print("Selected_service : \(selectedService)")
self.peripheral.discoverCharacteristics(nil, for:selectedService as CBService!)
//performSegue(withIdentifier: "mySegue", sender: nil)
// I used to performed segue here. This was the reason myCharacterisitcUUID was empty.
}
// find the characteristics for the targetService
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor targetService: CBService, error: Error?) {
if error != nil {
print("Characteristic NOT found : \(error)")
}
foundCharacteristics = targetService.characteristics!
for c in foundCharacteristics as [CBCharacteristic] {
self.myCharacteristicUUID.add(c.uuid)
}
// segue should be performed here ! This change worked!
performSegue(withIdentifier: "mySegue", sender: nil)
}
关于swift - segue中数据丢失(xcode8.0),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40483259/