jeudi 26 février 2015

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.




Aucun commentaire:

Enregistrer un commentaire