Doughnut Man Doughnut Man - 1 year ago 104
Swift Question

Saving Labels in NSUserDefault in Swift

So in the app I'm creating I have a settings view controller where users can type their information in the textfields and then when they click the done button it loads all that information to labels on the home view controller . How can I save the data in the home view controller with NSUserDefault? I'm using two view controllers.

Settings View Controller

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
let DestViewController = segue.destinationViewController as! home
DestViewController.NameText = NameTextField.text!
DestViewController.positionText = positionTextField.text!
DestViewController.divisionText = divisionTextField.text!
DestViewController.routeText = routeTextField.text!
DestViewController.routeText = routeTextField.text!
DestViewController._picture = _picture.image!


Home View Controller

class home: UIViewController, UITextFieldDelegate {
@IBOutlet weak var Name: UILabel!
@IBOutlet weak var position: UILabel!
@IBOutlet weak var division: UILabel!
@IBOutlet weak var route: UILabel!

var contacts = MyContacts()
var NameText = String()
var positionText = String()
var divisionText = String()
var routeText = String()
var _picture: UIImage!

override func viewDidLoad() {

Name!.text = NameText
position!.text = positionText
division!.text = divisionText
route!.text = routeText
Profile!.image = _picture

All of these codes work perfect, I'm just wondering if you could help me save the labels in NSUserDefault so every time the app is loaded all the information is still there. I've done a lot of research on this topic, but can find a solution for my problem. Any help would be much appreciated.

Answer Source

just use basic Syntax.

NSUserDefaults.standardUserDefaults().setValue(value, forKey:key)

Save Example:-

NSUserDefaults.standardUserDefaults().setValue(positionTextField.text!, forKey: "position")

Retervie Example:-


Note:- Remember key is must be unique

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download