Ruslan Pshichenko
Ruslan Pshichenko

Reputation: 3

Core Bluetooth Function

so I have been searching the web for the past couple days and still can't seem to find a solution that works. I'm running Core Bluetooth and am attempting to get data from an Arduino. Here's the code:

//Reading Bluetooth Data
func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
    let data = characteristic.value
    if let str:String = String(data: data!, encoding: NSUTF8StringEncoding) {
        self.delegate?.serialDidReceiveString(str)
        print(str)
    }
} 

I could see the incoming data using print(str) without an issue, but how in the world would I transfer this received data to another swift file and eventually display it onto a UILabel? Every time I try to use str outside the function, Xcode keeps telling be "expected declaration". My attempt of the delegate is a follows:

protocol BluetoothSerialDelegate {
    func serialDidReceiveString(message: String)
}
extension BluetoothSerialDelegate {
    func serialDidReceiveString(message: String) {}
}

With this variable defined within the class that the function is located in. var delegate: BluetoothSerialDelegate! Though I get no errors, when I call

func serialDidReceiveString(message: String) {
        Label.text! = message
        print(message)
    }

Inside the ViewController, I am unable to see the data like I did when it called from the initial function. What could the issue possibly be?

Upvotes: 0

Views: 189

Answers (2)

pbush25
pbush25

Reputation: 5248

You have a delegate...why not use it? In the class you want to display the data in, conform to your delegate, and implement the delegate method serialDidReceiveString:. Then, when the data is received, the delegate method will be called in the other view, and you can then update your label.

Upvotes: 0

buckleyJohnson
buckleyJohnson

Reputation: 499

Declare the string in your h file so you have a global variable. Or you could just save it user User Defaults, that would make it easy to access from another file.

Upvotes: 0

Related Questions