在Xamarin iOS中存储和检索用户凭证 [英] Storing and Retrieving User Credentials in Xamarin iOS

查看:63
本文介绍了在Xamarin iOS中存储和检索用户凭证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Xamarin.iOS应用程序,需要用户登录才能查看内容.我有两个文本字段,一个用于用户名,一个用于密码.用户登录后,API返回成功.如何保存用户凭据,以便他们启动应用程序时自动登录?

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);
    }

谢谢.

推荐答案

您可以安装此插件,并且所有工作已为您完成: https://github.com/sameerkapps/SecureStorage ,nuget: https://www.nuget.org/packages/sameerIOTApps.Plugin.SecureStorage/.

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");

如果您不想使用它,请查看github存储库,看看他们是如何在iOS中使用它的: https://github.com/sameerkapps/SecureStorage/blob/master/SecureStorage/Plugin.SecureStorage.iOSUnified/SecureStorageImplementation.cs

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);
}

这篇关于在Xamarin iOS中存储和检索用户凭证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆