Read variable with Spark.SDK does not work


first I want to thank you that you made it really easy via Cocoapods to program a iOS app.
But on the other hand I have currently a problem with it. Maybe it is, because I am a not very experienced programmer.
When I try to get a value of a variable from my core I get following error:
'fatal error: unexpectedly found nil while unwrapping an Optional value’
Here is my swift code:

// list all connected cores
var myCore : SparkDevice?
SparkCloud.sharedInstance().getDevices { (sparkDevices:[AnyObject]!, error:NSError!) -> Void in
    if let e = error {
        println("Check your internet connectivity")
    else {
        if let devices = sparkDevices as? [SparkDevice] {
            for device in devices {
                if == "wifiduino" {
                    myCore = device

// read variable countDown from Core
myCore!.getVariable("countDown", completion: { (result:AnyObject!, error:NSError!) -> Void in
    if let e=error {
        println("Failed reading countdown from device")
    else {
        if let countDown = result as? Int {
            println("The countdown is \(countDown)")

I have done all teh steps of the bridging from Cocoa to Swift and I also get a positive logged in result, when I do not try to read the variable.
I also double checked the variable name, which is correct.

Does anybody have some idea what I have done wrong?

Best regards,

I had the same problem in the beginning.
When you call myCore!.getVariable(...) it needs some time to get the value of the variable from the device. If you use the variable directly after calling myCore!.getVariabe(...) the variable is still nil.
You have to use the NSNotificationCenter and post a notification when your variable got a new value so that the rest of your program knows that it can work with the new value now.

Yes, the reason is that you have two asynchronous processes running, and the variable read returns faster than the get device.

I think a better solution to the problem is to put the login and device confirmation in one thread, and execute nothing until that thread is completed. You can do that with a simple flag.

If you are building an app, eventually you will not want to log in from a stored value rather than code, so will naturally split up those functions. You can download my Xcode Swift project from GitHub at account BendrixL. I’ll have log on storage code up next week.

1 Like

Thank you so much Bendrix. Your hint fixes the problem immediately.
I set your GitHub account on my watch list to get news from you. :wink: