Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Rohit Das
Rohit Das
4,356 Points

Using Swift/CoreData to allow users to log in - error!

Hi all, I am building an app and I want to allow users to register, log in and log out of the app. This is the code I have:

@IBAction func registerButtonTapped(sender: AnyObject) {

    let userEmail = userEmailTextField.text
    let userPassword = userPasswordTextField.text
    let userConfirmPassword = confirmPasswordTextField.text

    if (userEmail.isEmpty || userPassword.isEmpty || userConfirmPassword.isEmpty) {

        displayMyAlertMessage("You haven't filled out all the fields.")


    if (userPassword != userConfirmPassword) {

        displayMyAlertMessage("Passwords do not match.")


    var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var newUser = NSEntityDescription.insertNewObjectForEntityForName("Users", inManagedObjectContext: context) as NSManagedObject

    newUser.setValue(userEmail, forKey: "username")
    newUser.setValue(userPassword, forKey: "password")


I am wondering how I can use the data I saved here and access it when I click the login button. I was using a different method for this earlier, but can someone help me figure out what to change? Here is my code for when a user clicks login:

@IBAction func loginButtonTapped(sender: AnyObject) {

    let userEmail = userEmailTextField.text
    let userPassword = userPasswordTextField.text

    let userEmailStored = NSUserDefaults.standardUserDefaults().stringForKey("userEmail")
    let userPasswordStored = NSUserDefaults.standardUserDefaults().stringForKey("userPassword")

    if (userEmailStored == userEmail && userPasswordStored == userPassword) {
        NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isUserLoggedIn")
        self.dismissViewControllerAnimated(true, completion: nil)

    else {
        var failAlert = UIAlertController(title: "Alert", message: "Your username or password is incorrect.", preferredStyle: UIAlertControllerStyle.Alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)
        self.presentViewController(failAlert, animated: true, completion: nil)


Please help! Pasan Premaratne Amit Bijlani

Thanks! Rohit Das