mnuno
mnuno

Reputation: 1

Keychain iOS not always storing values

I´m developing a couple of iOS applications and i need to share a element between them, that i want to store in the keychain. This element is used in a complex login process with 3 or 4 steps, in each one i need to read the value from the keychain, to do this i used the code bellow:

- (NSString *)installationToken
{
    KeychainItemWrapper *kw = [[KeychainItemWrapper alloc] initWithIdentifier:@"uuid" accessGroup:@"yyyyy.xxxxxxxxxxx"];   

    if (![kw objectForKey:(NSString*)kSecAttrAccount] || [[kw objectForKey:(NSString*)kSecAttrAccount] isEqualToString:@""]) {
        NSString *result;

        CFUUIDRef uuid;
        CFStringRef uuidStr;

        uuid = CFUUIDCreate(NULL);
        assert(uuid != NULL);

        uuidStr = CFUUIDCreateString(NULL, uuid);
        assert(uuidStr != NULL);

        result = [NSString stringWithFormat:@"%@", uuidStr];
        assert(result != nil);

        CFRelease(uuidStr);
        CFRelease(uuid);

        [kw setObject:result forKey:(NSString*)kSecAttrAccount];

        return result;
    } else {
        return [kw objectForKey:(NSString*)kSecAttrAccount];
    }

}

This all works well in almost every device but in some, users are complaining. So, i checked what my server is receiving, and saw that different values are being sent. I checked the code and in no other place i'm acessing/emptying this keychain element, what can be wrong with this? For the majority of devices this works like a charm but for some reason, in some devices, they aren't storing or retrieving well from the keychain. The problem happens in different invocation in the same application.

Upvotes: 0

Views: 518

Answers (1)

user1165756
user1165756

Reputation: 397

If you are using Apples' sample code for KeyChainWrapper, then main problem is sometimes randomly, SecItemCopyMatching fails and then the sample code has resetKeychainItem which will basically reset your keychain.

    if (! SecItemCopyMatching((CFDictionaryRef)tempQuery, (CFTypeRef *)&outDictionary) == noErr)
    {
        // Stick these default values into Keychain if nothing found.
        [self resetKeychainItem];
    }

In our app, we noticed similar problems, and so now we are using

https://github.com/carlbrown/PDKeychainBindingsController to do all keyChain related functionality. Now it works very well.

Upvotes: 1

Related Questions