Search code examples
iosswiftbluetooth-lowenergyuart

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


I have been using the Adafruit Basic-Chat as a reference.

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

I have customised the code to communicate with my custom built nordic BLE-module for a basic UART communication. 10 bytes to write and 10 bytes to read. I can read and write in the UartModuleViewController but soon as I create a new View Controller and try to use the same peripheral.writeValue the app seem to throw an error at the peripheral.writeValue line in my second ViewController. Can someone please help me on How to pass the same peripheral connected to various view controller scenes so that I can use the write/read functions similarly?

//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)

//This is my read code

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)

I want to use this same two blocks for reading and writing across all my view controllers? (I have 10 view controllers that I want to use the same blocks in all their classes) I'm a newbie to swift/iOS and there is only limited information available for references so I hope this will help more beginners like me. Please help. Thanks nar

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.

Thread 1: EXC_BREAKPOINT (code=1, subcode=0x10042b200)


Solution

  • I figured it out. Passing the connected peripheral from the array of scanned peripherals and referencing the service uuid to the peripheral when we want to access it from the central class and passing it using a segue to whichever view controller scene we want and referencing it to the central/main class so it doesn't get disconnected when we return to the home view controller scene. Thanks guys for references