lernerbot
lernerbot

Reputation: 903

Unable to read NSUserDefaults from Watch when iPhone app launched

I'm trying to figure out what state the Watch is in when the iPhone app launches.

On the watch, there are 3 buttons. When a button is pressed the following code is run:

if let watchDefaults = NSUserDefaults(suiteName: "group.mywatchkit") {
        watchDefaults.setInteger(1, forKey: "intstate")
        watchDefaults.synchronize()
    }

Then when the app is launched, in the viewDidLoad() method I try to retrieve the state:

if let watchDefaults = NSUserDefaults(suiteName: "group.mywatchkit"){

        let currentState = watchDefaults.integerForKey("intstate")

        if currentState != 0 {

            stateLabel.text = currentState.description
            switch currentState {
            case 1: 
                //do what state 1 needs
                println("current state is \(currentState)")

            case 2: 
                //do what state 2 needs
                println("current state is \(currentState)")
            case 3: 
                //do what state 3 needs
                println("current state is \(currentState)")


            default:
                println("default state")

            }

        } else {

            watchDefaults.setInteger(3, forKey: "intstate")
            stateLabel.text = "current state is 3"
        }

    }

Sadly I'm always getting the string "???" Am I missing something fundamental?

Because it returns 0 if there is no value and there for it will never be nil. So you just need to check if it is equal to 0.

Upvotes: 2

Views: 226

Answers (2)

Stefan Arentz
Stefan Arentz

Reputation: 34945

You are using different key names in your code: state and intstate

Upvotes: 2

Leo Dabus
Leo Dabus

Reputation: 236370

You should use NSUserDefaults method called stringForKey() to load your Strings. Just use the same method you used for the suitName (if let) to safely unwrap your String for that key. Try like this:

if let watchDefaults = NSUserDefaults(suiteName: "group.mywatchkit") {
    watchDefaults.setObject("buttonX", forKey: "state")
}
if let watchDefaults = NSUserDefaults(suiteName: "group.mywatchkit"){
    if let currentState = watchDefaults.stringForKey("state") {
        println(currentState)  // "buttonX"
    }
     else {
        println(false)
    }
}

Upvotes: 1

Related Questions