0

Hey I'm trying to get JSON (using Alamofire) and show it on a label. This is what I get from server:

{
 Value = 4
}

I wrote this:

let Value = (response.result.value!["Value"] as? NSString) ?? 0

let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
prefs.setObject(Value, forKey: "Value")
prefs.setInteger(1, forKey: "Value")
prefs.synchronize()

//I try to show it by this code on the other page:

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(true)
    self.valueLabel.text = prefs.valueForKey("Value") as? String
}

But nothing is showing.

1 Answer 1

1

'synchronize()' is that not naive - it is automatically invoked at periodic intervals (And by the way, has some performance penalty - it is not necessary to call it every time - iOS takes care of updating the defaults)

However, since in your case you need to know when the value is in, you should fix an observer (just fill in the object and the update label thing of yours):

    NotificationCenter.default.addObserver(forName: UserDefaults.didChangeNotification, object: nil, queue: OperationQueue.main) { _ in  /* update your label */ }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.