Search code examples
jsonswift2xcode7.3

How to show JSON data in a label? Swift 2


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.


Solution

  • '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 */ }