Coder Coder - 1 month ago 11
Swift Question

Retrieving data by NSUserDefaults Swift 2.0

Currently, my code for NSUserDefaults work fine. The only issue I have now is how can I send the data store to another page? I can get it now save the data, but how do I retrieve that same data via NSUserDefaults to a secondary page?

import UIKit

class MainTableViewController: UITableViewController, UITextFieldDelegate {

let userDefaults = NSUserDefaults.standardUserDefaults()

@IBOutlet weak var name: UITextField!

@IBAction func btnSave() {

if name.text == "" {

let alert = UIAlertController(title: "Data", message: "Missing Name.", preferredStyle: UIAlertControllerStyle.Alert)

alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)

}

else {

userDefaults.setObject(name.text, forKey:"name")

userDefaults.synchronize()
}
}

override func viewDidLoad() {

super.viewDidLoad()

}

override func viewDidAppear(animated: Bool) {

name.text = userDefaults.stringForKey("name")
}
}

Answer

You can retrieve your data from your second page with same code. Create your NSUserDefaults in second page like this ;

First of all add these codes to your FirstPage in IBAction func. Don't use the if else statement for test.

UserDefaults.standard.set("yourValue", forKey: "yourKey")

When you press the button it should be save your data with your key.

In the secondPage you can retrieve your data in your viewDidLoad method like this;

override func viewDidLoad() {
super.viewDidLoad()
print(UserDefaults.standard.value(forKey: "yourKey") ?? "defaultValue in case key is not found")
print(value)
}

It should be print your value to your console (bottom window in your xcode) when the secondPage is open. If you still can't retrieve your value please share to me a your storyboard picture. I want to see your connections.

Comments