我似乎无法从钥匙串中获取值,因为它始终返回ItemNotFound。我正在使用的代码如下:
private static Guid GetID()
{
Guid returnGuid = Guid.Empty;
SecStatusCode code;
SecRecord queryRec = new SecRecord (SecKind.GenericPassword) { Service = KEYCHAIN_SERVICE, Label = KEYCHAIN_SERVICE, Account = KEYCHAIN_ACCOUNT };
queryRec = SecKeyChain.QueryAsRecord (queryRec, out code);
if (code == SecStatusCode.Success && queryRec != null && queryRec.Generic != null )
{
returnGuid = new Guid(NSString.FromData(queryRec.Generic, NSStringEncoding.UTF8));
}
return returnGuid;
}
当我尝试设置值时,它返回DuplicateItem并使用以下代码:
private static SecStatusCode SetID (Guid setID)
{
SecStatusCode code = SecKeyChain.Add (new SecRecord (SecKind.GenericPassword) {
Service = KEYCHAIN_SERVICE,
Label = KEYCHAIN_SERVICE,
Account = KEYCHAIN_ACCOUNT,
Generic = NSData.FromString(Convert.ToString(setID), NSStringEncoding.UTF8),
Accessible = SecAccessible.Always
} );
return code;
}
任何帮助都会很棒!
答案 0 :(得分:3)
我将您的代码复制粘贴到Touch.Unit解决方案中,它可以在模拟器和设备上运行。
[Test]
public void CheckId ()
{
Guid g = Guid.NewGuid ();
SetID (g);
Assert.That (g, Is.EqualTo (GetID ()), "same guid");
}
我唯一要改变的是你的KEYCHAIN_*
常量字符串,我保持相同的值(即只添加引号)。
现在,如果您执行代码第二次时间,您将收到DuplicateItem
错误代码,因为SetID
正在尝试设置相同的项再次当你查询Guid
时,你会得到第一个 - 导致错误。
您有两个选择,删除现有项目或更新它。例如。删除现有项目......
static SecStatusCode SetID (Guid setID)
{
SecRecord queryRec = new SecRecord (SecKind.GenericPassword) {
Service = "KEYCHAIN_SERVICE",
Label = "KEYCHAIN_SERVICE",
Account = "KEYCHAIN_ACCOUNT"
};
var record = new SecRecord (SecKind.GenericPassword) {
Service = "KEYCHAIN_SERVICE",
Label = "KEYCHAIN_SERVICE",
Account = "KEYCHAIN_ACCOUNT",
Generic = NSData.FromString (Convert.ToString (setID), NSStringEncoding.UTF8),
Accessible = SecAccessible.Always
};
SecStatusCode code = SecKeyChain.Add (record);
if (code == SecStatusCode.DuplicateItem) {
code = SecKeyChain.Remove (queryRec);
if (code == SecStatusCode.Success)
code = SecKeyChain.Add (record);
}
return code;
}
注意:测试时我从未得到ItemNotFound
。