swift - segue中数据丢失(xcode8.0)

标签 swift xcode bluetooth-lowenergy segue

我是 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/

相关文章:

ios - SWIFT:更新现有的核心数据对象

ios - Button.setImage(nil,对于 : . 正常)在 iOS 15 中不起作用

ios - 当我尝试存档时,无法创建 ipa 文件

ios - 从命令行导入 xcode 方案

objective-c - 场景的 Sprite 套件快速边界

android - 连接到无法在 Samsung Galaxy Core Prime (Android 5.1.1) 上运行的 gatt 服务器

android - 如何确保 UUID 对于我的 BLE 服务或特性是唯一的?

ios - Facebook iOS SDK 没有 FBSDKApplicationDelegate 类及其方法

iOS Bluetooth LE - 无响应写入的正确方法

ios - 在 Swift 中导入 C 头文件