简体   繁体   中英

Can't access saved in a Xamarin.iOS keychain value

In my app I have two methods which help me save and get values from keychain

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

I'm saving there two values and for some reason when I try to get any of them I get an "Error" string instead of the value. The same code previously worked without any problems, but then I added another parameter to store in the keychain and renamed both

If you are targeting iOS 10+, make sure you are checking the return status of your SecKeyChain.Add :

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

If you are getting a -34018 , then you need to enable KeyChain access in your Entitlements.plist :

在此处输入图片说明

And then make sure that the Entitlements.plist is assigned to your Custom Entitlements in your Project Build / iOS Bundle Signing :

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM