我正在使用Xamarin.Auth来保存凭据并且用户登录Xamarin Forms应用程序。 现在,我需要实现一个"切换登录用户"但我不知道如何正确地做到这一点。
互联网没什么。所以,如果有人可以解释或说明这是怎么做的。
检查是否已保存帐户:
IEnumerable<Account> accounts = AccountStore.Create().FindAccountsForService(InstaConstants.AppName);
但总是只有一个帐户,我正在测试而不删除旧凭据。
答案 0 :(得分:1)
查看this示例。它显示了一旦用户登录,调用Completed
事件,您检查以确保他们已登录,然后保存access_token
中存储的eventArgs.Account.Properties["access_token"]
:
auth.Completed += (sender, eventArgs) => {
if (eventArgs.IsAuthenticated) {
App.Instance.SuccessfulLoginAction.Invoke();
// Use eventArgs.Account to do wonderful things
App.Instance.SaveToken(eventArgs.Account.Properties["access_token"]);
} else {
// The user cancelled
}
};
*修改:要在AccountStore
中保存多个帐户,您只需提供不同的provider
值:
//FROM
await AccountStore.Create().SaveAsync(eventArgs.Account, "instagram"); //Saving a single general Instagram account
//TO
string someUniqueIdentifier = /* the user's User Id, an incremented number, some other identifier */
await AccountStore.Create().SaveAsync(eventArgs.Account, "instagram" + someUniqueIdentifier); //Ability to save multiple Instagram accounts, someUniqueIdentifier must change for each new account
答案 1 :(得分:1)
如果您只使用1个商店没有限制,您可以为商店命名,例如&#34; MySupaApp&#34; + iteration.ToString();所以你将迭代你保存的所有用户。
另一种简洁的方法是使用json将您的用户列表保存到一个帐户中。
//im using Constants.StoreName - you know what it is..
//
//save users
//
List<MyUsers> MyList; // <==users here initially
var jsonUsers = await Task.Run(() => JsonConvert.SerializeObject(MyList));
Account account = new Account();
account.Username = "AllMyUsers";
account.Properties.Add("users", jsonUsers);
//cleanup previous
var accounts = store.FindAccountsForService(Constants.StoreName).ToList();
accounts.ForEach(acc => store.Delete(acc, Constants.StoreName));
//save finally
await store.SaveAsync(account, Constants.StoreName);
//
//read users
//
Account account = store.FindAccountsForService(Constants.StoreName).FirstOrDefault();
if (account == null)
{
//create new empty list of users
//todo
return false;
}
try
{
List<MyUsers> MyList = JsonConvert.DeserializeObject<List<MyUsers>>(account.Properties["users"]);
//todo check stuff if list is valid
return true;
}
catch
{
//todo
//create new empty list
//something went wrong
}