Keychain errSecItemNotFound

Hello Apple Developer: I encountered some issues during development. I encrypted the secret key and stored it in the Keychain, but it failed when I tried to read it. I would like to ask if there is any problem with the code I wrote. Below is my code, including the storage and retrieval

NSMutableDictionary *query = [[NSMutableDictionary alloc] initWithObjectsAndKeys:(id)kSecClassGenericPassword,(id)kSecClass,

                                  serviceID,(id)kSecAttrService,

                                  @YES,(id)kSecReturnData,nil];

    

    CFTypeRef dataTypeRef = NULL;

    NSLog(@"SecItemCopyMatching");

    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)(query), &dataTypeRef);

    NSLog(@"SecItemCopyMatching end status = %d",status);

    if (status == errSecSuccess) {

        

        *privateData = CFBridgingRelease(dataTypeRef);

        return 0;

        

    }else{

        

        return status;

        

    }
NSMutableDictionary *attributespri = [[NSMutableDictionary alloc] initWithObjectsAndKeys:

        (id)kSecClassGenericPassword, (id)kSecClass,

        serviceID,                   (id)kSecAttrService,

        outData,                     (id)kSecValueData,

    nil];



    CFTypeRef dataRef = NULL;

    OSStatus priStatus = SecItemAdd((__bridge CFDictionaryRef)attributespri, &dataRef);



    if (dataRef) CFRelease(dataRef);

    return priStatus == noErr;
Answered by DTS Engineer in 884212022

I’m gonna start you out with SecItem: Fundamentals. It explains how you should think about the keychain. Once you internalise that, a lot of its behaviour makes sense.

As to what’s going on here, it’s hard to say without more context. My first question is: What platform are you on?

This matters because, if you’re on the Mac, the keychain has a lot of additional complexity. TN3137 On Mac keychain APIs and implementations explains the details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I’m gonna start you out with SecItem: Fundamentals. It explains how you should think about the keychain. Once you internalise that, a lot of its behaviour makes sense.

As to what’s going on here, it’s hard to say without more context. My first question is: What platform are you on?

This matters because, if you’re on the Mac, the keychain has a lot of additional complexity. TN3137 On Mac keychain APIs and implementations explains the details.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

I am using the iOS platform. I would like to ask: when using kSecClassGenericPassword, is the kSecAttrAccount attribute required? I did not set kSecAttrAccount and kSecAttrAccessible when saving data on older iOS versions. Will this cause problems when querying Keychain items on iOS 26?

Keychain errSecItemNotFound
 
 
Q