Peng Zhanglong Peng Zhanglong - 6 months ago 34
Swift Question

swift display default username

@IBOutlet weak var studyID: UITextField!
@IBOutlet weak var userID: UITextField!

let username: String = self.studyID.text!
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(username, forKey: "username")


How am I able to store the username and display when next time I open this app?

Answer

put this in viewDidAppear()

override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)
    username = NSUserDefaults.standardUserDefaults().objectForKey("username") as! String
    print(username)
}

make sure you save successfully.

let username: String = self.studyID.text!
let defaults = NSUserDefaults.standardUserDefaults()    
defaults.setObject(username, forKey: "username")
defaults.synchronize()