Monday, February 18, 2013

Monotouch NSDefaults and useful Keychain code.


Just some useful code.

public static class KeychainHandler
    {
        public static SecStatusCode HasCredentials(string generic)
        {
            var record = new SecRecord (SecKind.GenericPassword)
            {
                Generic = NSData.FromString(generic)
            };
            SecStatusCode result;
            var match = SecKeyChain.QueryAsRecord (record, out result);
            return result;
        }
        public static SecRecord Credentials(string generic)
        {
            var record = new SecRecord (SecKind.GenericPassword)
            {
                Generic = NSData.FromString(generic)
            };
            SecStatusCode result;
            var match = SecKeyChain.QueryAsRecord (record, out result);
            return match;
        }
        public static void DeleteKeychain(string generic)
        {
            SecKeyChain.Remove(KeychainHandler.Credentials(generic));
        }
}

To save NSDefaults for a User :

NSUserDefaults.StandardUserDefaults.SetString(yourstringvalue,yourstringkey);
NSUserDefaults.StandardUserDefaults.Init();

To Retrieve :

if(NSUserDefaults.StandardUserDefaults["whatever"] != null)
{
string value = NSUserDefaults.StandardUserDefaults.StringForKey("whatever");
}

No comments:

Post a Comment