Search code examples
swifttimercore-bluetooth

How to write to a bluetooth peripheral on a timer (1 sec), without the timer duplicating when the class is being referenced in multiple views


To receive data from my bluetooth peripheral I need to write bytes to it (every time I write I get a response). The goal is to automaticly write to the peripheral every 1 second and to be able to view the data and trigger functions from the class in multiple views.

The problem I currently face is where to put the timer, I currently set it up here

override init() { 
     Super.init()
     //I put the timer in this spot 
} //(in my bluetooth class)

Which I thought worked fine until I noticed that every time that I reference the class in a view struct the timer duplicates.

let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
            print("Timer fired!")
            self.WriteData() //function to write data to the peripheral
        }
struct ViewBluetoothData: View { //I have two similar views to this
    @ObservedObject var BluetoothData = BluetoothClass() //This seems to duplicate the timer
    var body: some View {
           //View where I get data from the class and trigger functions in the class
           //Example:
           Text("Voltage: \(BluetoothData.Voltage)")
           Button {BluetoothData.WriteData(Data: [0x00])} label: {Text("Write Data")}
     }
}

Currently I reference the class 3 times which causes the timer to fire 3 times and thus write 3 times to the peripheral.

I also tried to put a timer in a view (it won't duplicate that way), but that causes this error: "Bluetooth and interface combined[3578:1298595] [CoreBluetooth] XPC connection invalid" and tried to put it elsewhere in the bluetooth class, but with no succes either (all kinds off trouble with "self")

I'am relatively new to swift and couldn't find my anwser in other questions about timers. Any help is greatly appreciated! Hope I explained my problem good enough.


Solution

  • It does not duplicate the Timer it creates a new Class instance with a new Timer, you can try and use a singleton for the beginning - forcing only one instance of the class. A long-run solution will be to use some Dependency Injection solution to control the class lifecycle