How to use Keychain in ios programming

18,343

Solution 1

Use PDKeyChainBindings

This is how to use:

PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings];
[bindings setObject:@"myuser" forKey:@"username"];
[bindings setObject:@"kmypass" forKey:@"password"];

//How to retrieve
NSString *username = [bindings objectForKey:@"username"];
NSString *password = [bindings objectForKey:@"password"];

Solution 2

you can save your credential info more securely using keychain access. For that please follow bellow guides and Samples.

1) Keychain Services Programming Guide

You found all as your want in this document by apple.

2) GenericKeychain

This sample code by apple shows how to add, remove and update keychain values.

Let me know if you have any problem in this. Hope this one helpful to you.

Solution 3

#import "SFHFKeychainUtils.h"
#define KEYCHAIN_SERVICE_KEY   @"MyKey"
#define KEYCHAIN_ID @"agsfs46edt3g3jd38jh3g3g3g3g38f3dkiuytr453"
#define KEYCHAIN_PSD @"a1s2s3d4edt3g3jd38jh3g3g3g3g38f3dfgffgdd"

//to check

NSError *error = nil;
    NSString *password = [SFHFKeychainUtils getPasswordForUsername:KEYCHAIN_ID andServiceName:KEYCHAIN_SERVICE_KEY error:&error];

    if ([password isEqualToString:KEYCHAIN_PSD])
        return YES;

//to save

NSError *error = nil;
        [SFHFKeychainUtils storeUsername:KEYCHAIN_ID  andPassword:KEYCHAIN_PSD forServiceName:KEYCHAIN_SERVICE_KEY updateExisting:YES error:&error];
Share:
18,343
Pradeep Rajkumar
Author by

Pradeep Rajkumar

Senior Software engineer | iPhone/iPad Applications Developer

Updated on June 05, 2022

Comments

  • Pradeep Rajkumar
    Pradeep Rajkumar almost 2 years

    I'm using the Keychain wrapper class provided by Apple. In my application I want to store and retrieve the username and password of the logged in user. When the app is launched again, it should check for the login credentials in the keychain and let the user into the app(automatic login). Tried some sample codes. nothing worked out. Please help me out with the procedure to do this.

    Thanks.