Save user information when logging in for later use

I am creating an application where, upon entering the system, the correct username / password combination returns some basic user information (firstName, lastName, userType, companyID, etc.).

I will need these values ​​and strings in my application to get user data.

Can I save all these values ​​and strings when I enter a subclass of NSObject or NSData so that I can call it later to get the elements I need? How can i do this? or is there a better alternative?

+4
source share
3 answers

If you just save the data received from a successful login, as you say: first name, last name, etc. I would use NSUserDefaults. If you intend to store any confidential information, such as a username or password or anything else that requires additional confidentiality, I would recommend using a keychain.

+6
source

I would use Keychain as it is safe. Check out STKeychain

+4
source

You can use NSUserDefaults . Create a user model. Implement the NSCoding protocol. Archive during storage and unpacking when retrieving from NSUserDefaults .

 @interface User: NSObject<NSCoding> @property (nonatomic, copy) NSString *firstName; @property (nonatomic, copy) NSString *lastName; - (void)save; + (id)savedUser; 

//User.m

 #define kSavedUser @"SavedUser" #pragma mark - Encoding - (void)encodeWithCoder:(NSCoder *)encoder { [encoder encodeObject:self.firstName forKey:@"FirstName"]; [encoder encodeObject:self.lastName forKey:@"LastName"] } #pragma mark - Decoding - (id)initWithCoder:(NSCoder *)decoder { self = [super init]; if (self) { _firstName = [decoder decodeObjectForKey:@"FirstName"]; _lastName = [decoder decodeObjectForKey:@"LastName"]; } return self; } -(void)save { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self]; [defaults setObject:data forKey:kSavedUser]; [defaults synchronize]; } + (id)savedUser { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults objectForKey:kSavedUser]; if (data) { return [NSKeyedUnarchiver unarchiveObjectWithData:data]; } return nil; } + (void)clearUser { NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults removeObjectForKey:kSavedUser]; [defaults synchronize]; } 

Now you can create an instance

 User *user = [[User alloc]init]; user.firstName = @""; user.lastName = @""; [user save]; 

If you want to get

 User *user = [User savedUser]; 

EDIT: If you want to clear the data, call the static method to delete the stored user information

 [User clearUser]; 
+3
source

All Articles