无法访问保存在Xamarin.iOS钥匙串值中

在我的应用程序中,我有两种方法可以帮助我保存并获取钥匙串的值

public static void StoreKeysInKeychain(string key, string value) { DeleteKeyFromKeychain(key); var s = new SecRecord(SecKind.GenericPassword) { ValueData = NSData.FromString(value), Generic = NSData.FromString(key) }; SecKeyChain.Add(s); Console.WriteLine(GetRecordsFromKeychain(key)); } public static string GetRecordsFromKeychain(string key) { SecStatusCode res; var rec = new SecRecord(SecKind.GenericPassword) { Generic = NSData.FromString(key) }; var match = SecKeyChain.QueryAsRecord(rec, out res); if (match != null) return match.ValueData.ToString(); return "Error"; } 

我保存有两个值,由于某种原因,当我试图得到他们中的任何一个我得到一个“错误”string,而不是值。 以前相同的代码没有任何问题,但我添加了另一个参数存储在钥匙串中,并重命名

如果您的目标是iOS 10+,请确保您正在检查SecKeyChain.Add的返回状态:

 var status = SecKeyChain.Add(s); if (status == SecStatusCode.Success) Console.WriteLine(GetRecordsFromKeychain(key)); else Console.WriteLine(status); 

如果你得到了-34018 ,那么你需要在你的Entitlements.plist启用KeyChain访问:

在这里输入图像说明

然后确保将Entitlements.plist分配给您的项目Build / iOS Bundle Signing Custom Entitlements

在这里输入图像说明