I have three text fields in one view controller and I want to save save each input the user puts.
I have no idea on how to save data so I need help. It is three pieces of information that makes the user create an account. The user will use it to log into his account. Do I need to make an array of text fields? If so, how?
Asked
Active
Viewed 131 times
0

Brian Tompsett - 汤莱恩
- 5,753
- 72
- 57
- 129

user3462406
- 15
- 1
- 3
- 7
-
1Use `NSUserDefaults` for non-secure information, and use the keychain for secure information. – Léo Natan Mar 28 '14 at 01:30
-
possible duplicate of [iOS: How to store username/password within an app?](http://stackoverflow.com/questions/6972092/ios-how-to-store-username-password-within-an-app) – Neal Ehardt Mar 28 '14 at 01:41
1 Answers
0
You should use the KeychainItemWrapper
class for storing secure data.
First download the .h and .m files at this github link.
Now add them to your project by drag and drop. Don't forget to do this:
In your app, navigate to
Build phases -> Link Libraries
and add Security.framework
.
Now in your viewController
's implementation file, import the class you have just added.
#import "KeychainItemWrapper.h"
Suppose you have three textField
s for entering username email and password, you create outlets for them as:
@property (weak, nonatomic) IBOutlet UITextField *userNameTextField;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *emailTextField;
Now, in you signUpButtonClick
method you can store these fields using the following code:
- (IBAction)signUpButtonClick:(id)sender
{
[keychainItem setObject:self.emailTextField.text forKey:(__bridge id)kSecAttrService];
[keychainItem setObject:self.passwordTextField.text forKey:(__bridge id)kSecValueData];
[keychainItem setObject:self.userNameTextField.text forKey:(__bridge id)kSecAttrAccount];
}
Later, if you want to retrieve these fields, you can simply get them using the following code:
NSString *email = [keychainItem objectForKey:(__bridge id)kSecAttrService];
NSString *password =
[[NSString alloc] initWithData:[keychainItem objectForKey:(__bridge id)kSecValueData] encoding:NSUTF8StringEncoding];
NSString *username = [keychainItem objectForKey:(__bridge id)kSecAttrAccount];
Note:
- The password field is stored as data as we use the key kSecValueData. So it should be converted to string for viewing purposes. This is what I have done above.
- (__bridge id) should be used only in ARC projects.
Hope this helps! :)