Question

I am making an IOS app in which I have some extra things for registered user so I made login form and it works perfectly but every time I run simulator I have to login so I just want to ask that how can I store the login user that when an registered user is login first time then login page opened but after login when user close their app and run again then its open next page from login.

Was it helpful?

Solution 3

// create a standardUserDefaults variable
NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];

// saving an NSString
[standardUserDefaults setObject:@"YES" forKey:@"Login"];

[standardUserDefaults synchronize];

//Check For Login
// create a standardUserDefaults variable
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

// getting an NSString object
NSString *Isallowed = [standardUserDefaults stringForKey:@"Login"];
if(Isallowed == @"YES"){
   // Process for login
}
else
{
   // Alert them for Not login
}

OTHER TIPS

use NSUserDefaults to store the flag variable to check the login status

For Saving Username and Password I will personally suggest to use Keychain as they are more safer than NSUserDefault in terms of security since Keychain stores data in encrypted form while NSUserDefault stores as plain text. If you still want to use NSUserDefault Here's the way

// create a standardUserDefaults variable

NSUserDefaults * standardUserDefaults = [NSUserDefaults standardUserDefaults];

// saving an NSString

[standardUserDefaults setObject:@"YES" forKey:@"Login"];

[standardUserDefaults synchronize];

//Check For Login // create a standardUserDefaults variable

NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];

// getting an NSString object

NSString *Isallowed = [standardUserDefaults stringForKey:@"Login"];
if(Isallowed == @"YES"){
   // Process for login
}
else
{
}

I'm gonna give you a comprehensive answer.

Don't use NSUserDefaults and don't store password it's a bad solution

NSUserDefaults data is not encrypted, it may cause security issue.

Let's create a structured user class instead

When the user logged in, you will need to make sure you have access to user data throughout the app so you can get the data on any screen when you need it.

To achieve this, we need to make a great structure to organize this properly. Remember that current user and another users are both "user" so we will use the same class.

Create a class and name it "EDUser" (you can choose other name if you want).
This class will contain a user information (either current user or other user).
More than that, this class will have capability to log the user in.

Here's a picture of what the class might look like:

class EDUser {
    var firstName: String
    var lastName: String?
    var birthDate: NSDate?

    init(firstName: String, lastName: String?, birthDate: NSDate?) {
        self.firstName = firstName
        self.lastName = lastName
        self.birthDate = birthDate
    }
}

// MARK: - Accessor

extension EDUser {
    class var currentUser: EDUser? {
        get {
            return loadCurrentUserFromDisk()
        }
        set {
            saveCurrentUserToDiskWithUser(newValue)
        }
    }
}

// MARK: - Log in and out

extension EDUser {
    class func loginWithUsername(username: String,
                           andPassword password: String,
                           callback: (EDUser?, NSError) -> Void) {
        // Access the web API
        var parameters = [
            "username": username,
            "password": password
        ]
        YourNetworkingLibrary.request(.POST,
                          "https://api.yourwebsite.com/login",
                          parameters: parameters).responseJSON { 
            response in

            if response.statusCode == .Success {
                let user = EDUser(firstName: response["firstName"],
                       lastName: response["lastName"],
                       birthDate: NSDate.dateFromString(response["birthDate"]))
                currentUser = user
                callback(currentUser, nil)
            } else {
                callback(nil, yourError)
            }
        }
    }

    class func logout() {
        deleteCurrentUserFromDisk()
    }
}

// MARK: - Data

extension EDUser {
    class private func saveCurrentUserToDiskWithUser(user: EDUser) {
        // In this process, you encode the user to file and store it
    }

    class private func loadCurrentUserFromDisk() -> EDUser? {
        // In this process, you get the file and decode that to EDUser object
        // This function will return nil if the file is not exist
    }

    class private func deleteCurrentUserFromDisk() {
        // This will delete the current user file from disk
    }
}

// MARK: - Helper

extension NSDate {
    class func dateFromString(string: String) -> NSDate {
        // convert string into NSDate
    }
}

Use Case

Now with everything in place, we can use it like this

Non-blocking logging in process

EDUser.loginWithUsername(username: "edward@domain.com",
                         password: "1234") {
    user, error in

    if error == nil {
        // Login succeeded
    } else {
        // Login failed
    }
}

Logging out

EDUser.logout()

Check whether the user is logged in

if EDUser.currentUser != nil {
    // The user is logged in
} else {
    // No user logged in
    // Show the login screen here
}

Get current user data on any screen

if let currentUser = EDUser.currentUser {
    // do something with current user data
}

Store other user as object

let user = EDUser(firstName: "Edward",
                  lastName: "Anthony",
                  birthDate: NSDate())
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top