Swift-BLE-UART 如何从各种视图控制器场景中read/write?

Swift-BLE-UART How to read/write from various view controller scenes?

我一直在使用 Adafruit Basic-Chat 作为参考。

https://github.com/adafruit/Basic-Chat/tree/master/Basic%20Chat

我已经自定义了代码来与我自定义的北欧 BLE 模块进行通信,以进行基本的 UART 通信。 写入 10 个字节,读取 10 个字节。 我可以在 UartModuleViewController 中读写,但是当我创建一个新的 View Controller 并尝试使用相同的 peripheral.writeValue 时,应用程序似乎在我的 peripheral.writeValue 行抛出错误第二 ViewController。 有人可以帮助我如何将相同的外围设备连接到各种视图控制器场景,以便我可以类似地使用 write/read 功能吗?

//This is my write code
let bytes : [UInt8] = [ 0x1A, 0x2B, 0x3C, 0x4D ]
        let Transmitdata = NSData(bytes: bytes, length: bytes.count)
        peripheral.writeValue(Transmitdata as Data, for: txCharacteristic!, type: CBCharacteristicWriteType.withoutResponse)
        print("Data Sent",Transmitdata)

//这是我的阅读代码

let ReceiveData = rxCharacteristic?.value
        if let ReceiveData = ReceiveData {
            let ReceivedNoOfBytes = ReceiveData.count
            var ReceivedByteArray = [UInt8](repeating: 0, count: ReceivedNoOfBytes)
            (ReceiveData as NSData).getBytes(&ReceivedByteArray, length: ReceivedNoOfBytes)
            print("Data Received ",ReceivedByteArray)

我想使用这两个相同的块来读取和写入我所有的视图控制器吗? (我有 10 个视图控制器,我想在它们的所有 类 中使用相同的块) 我是swift/iOS的新手,可供参考的信息有限,所以我希望这能帮助更多像我这样的初学者。 请帮忙。 谢谢 纳尔

0x1000d9b78 <+2408>:  uxtb   w2, w9
    0x1000d9b7c <+2412>:  uxtb   w5, w9
    0x1000d9b80 <+2416>:  mov    x6, x10
    0x1000d9b84 <+2420>:  bl     0x1000e0174               ; symbol stub for: function signature specialization <preserving fragile attribute, Arg[2] = Dead, Arg[3] = Dead> of Swift._fatalErrorMessage(Swift.StaticString, Swift.StaticString, file: Swift.StaticString, line: Swift.UInt, flags: Swift.UInt32) -> Swift.Never
    0x1000d9b88 <+2424>:  ldr    x8, [x19, #0xab8].  <- This is where it throws an error/exception/fatal error.

线程 1:EXC_BREAKPOINT(代码=1,子代码=0x10042b200)

我想通了。 当我们想从中央 class 访问它时,从扫描的外围设备数组中传递连接的外围设备并将服务 uuid 引用到外围设备,并使用 segue 将其传递到我们想要的任何视图控制器场景并将其引用到central/main class 所以当我们 return 到主视图控制器场景时它不会断开连接。 感谢大家的参考