Storing and Retrieving User Credentials in Xamarin iOS

£可爱£侵袭症+ 提交于 2019-12-08 15:20:52

问题


I have a Xamarin.iOS application that requires users to log-in in order to view content. I have two text fields, one for username and one for password. Once a user has logged in and the API has returned success. how can I save the users credentials so when they launch the app they get signed in automatically?

I tried this, however, I don't know how to retrieve the values or re-save credentials if user logs out

void StoreKeysInKeychain(string key, string value)
    {

        var s = new SecRecord(SecKind.GenericPassword)
        {
            ValueData = NSData.FromString(value),
            Generic = NSData.FromString(key)
        };
        var err = SecKeyChain.Add(s);
    }

Thanks.


回答1:


Better to use iOS default NSUserDefaults.StandardUserDefaults to store your credentials.

Check for stored value in Login ViewController, if it doesn't exist then after successful login set the user name and password to "GetStoredCredentials" else fetch the saved credentials and use.

public String GetStoredCredentials
{
    get { 
        string value = NSUserDefaults.StandardUserDefaults.StringForKey("Key"); 
        if (value == null)
            return "";
        else
            return value;
    }
    set {
        NSUserDefaults.StandardUserDefaults.SetString(value.ToString (), "Key"); 
        NSUserDefaults.StandardUserDefaults.Synchronize ();
    }
}

Either you can save as string array or comma seperated value. Let me know for any further assistance. For your refrence : https://developer.xamarin.com/guides/ios/application_fundamentals/user-defaults/




回答2:


You can install this plugin and all of the work is already done for you: https://github.com/sameerkapps/SecureStorage, nuget: https://www.nuget.org/packages/sameerIOTApps.Plugin.SecureStorage/.

If you use the plugin it is as simple as:

CrossSecureStorage.Current.SetValue("SessionToken", "1234567890");
var sessionToken = CrossSecureStorage.Current.GetValue ("SessionToken");

If you don't want to use it, then look into github repo and see how they did it for iOS: https://github.com/sameerkapps/SecureStorage/blob/master/SecureStorage/Plugin.SecureStorage.iOSUnified/SecureStorageImplementation.cs

public override string GetValue(string key, string defaultValue)
{
    SecStatusCode ssc;
    var found = GetRecord(key, out ssc);
    if (ssc == SecStatusCode.Success)
    {
        return found.ValueData.ToString();
    }

    return defaultValue;
}

private SecRecord GetRecord(string key, out SecStatusCode ssc)
{
    var sr = new SecRecord(SecKind.GenericPassword);
    sr.Account = key;
    return SecKeyChain.QueryAsRecord(sr, out ssc);
}


来源:https://stackoverflow.com/questions/47058594/storing-and-retrieving-user-credentials-in-xamarin-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!