Haagenti
Haagenti

Reputation: 8144

iOS KeyChain secItemAdd crash

I'm trying to work with KeyChain and without a wrapper. But my code crashes when I want to read the value.

Code:

CFDictionaryRef attributes = CFDictionaryCreate(NULL, keys, values, 5, NULL, NULL);

CFDataRef result;
OSStatus status = SecItemAdd(attributes, (CFTypeRef *)&result);
if (status == errSecSuccess) {
  if (result && CFGetTypeID(result) == CFDataGetTypeID()) { //crashes here
    NSLog(@"Data");

  }


  isSuccess = YES;
} else {
  fprintf(stderr, "Error while inserting into keychain osstatus:%ld\n", status);
}

Error: EXC_BAD_ACCESS

What am I doing wrong? I thought SecItemAdd can return the newly add item

Edit:

const void *keys[] = {
    kSecClass
  , kSecAttrAccessible
  , kSecAttrService
  , kSecAttrAccount
  , kSecValueData
};

const void *values[] = {
    kSecClassGenericPassword
  , kSecAttrAccessibleWhenUnlocked
  , (__bridge CFStringRef)service
  , (__bridge CFStringRef)account
  , data //CFDataRef
};

Upvotes: 0

Views: 2115

Answers (2)

Jon Boydell
Jon Boydell

Reputation: 834

The answer to why you're getting EXC_BAD_ACCESS, is because the dictionary that you pass into SecItemAdd has to be mutable.

Try something like this:

CFMutableDictionaryRef attributes = CFDictionaryCreateMutable(NULL, size, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks);

CFDictionaryAddValue(attributes, keys[x], values[x]);

Upvotes: -1

valfer
valfer

Reputation: 3545

From documentation:

To obtain the data of the added item as an object of type CFDataRef, specify the return type key kSecReturnData with a value of kCFBooleanTrue.

Upvotes: 2

Related Questions