Search code examples
iosuuidkeychain

How to Save UUID in the keychain iOS?


i am newbie in iOS Development and i want to store my Application UUID in KeyChain so For any Time my Application UUID remaining same i do R&D on it and Find a code from this Site i mess StackOver Flow the Code is like as

+(NSUUID *)persistentIdentifierForVendor
{
static NSString * const kKeyChainVendorID = @"co.cwbrn.PersistentIdentifier";
static NSString * const kKeyChainVendorIDAccessGroup = @"<AppIdentifier>.<keychain-access-group-identifier>";

// First, check NSUserDefaults so that we're not hitting the KeyChain every single time
NSString *uuidString = [[NSUserDefaults standardUserDefaults] stringForKey:kKeyChainVendorIDGroup];
BOOL vendorIDMissingFromUserDefaults = (uuidString == nil || uuidString.length == 0);

if (vendorIDMissingFromUserDefaults) {
    // Check to see if a UUID is stored in the KeyChain
    NSDictionary *query = @{
                            (__bridge id)kSecClass:             (__bridge id)kSecClassGenericPassword,
                            (__bridge id)kSecAttrAccount:       kKeyChainVendorID,
                            (__bridge id)kSecAttrService:       kKeyChainVendorID,
                            (__bridge id)kSecAttrAccessGroup:   kKeyChainVendorIDAccessGroup,
                            (__bridge id)kSecMatchLimit:        (__bridge id)kSecMatchLimitOne,
                            (__bridge id)kSecReturnAttributes:  (__bridge id)kCFBooleanTrue
                           };
    CFTypeRef attributesRef = NULL;
    OSStatus result = SecItemCopyMatching((__bridge CFDictionaryRef)query, &attributesRef);
    if (result == noErr) {
        // There is a UUID, so try to retrieve it
        NSDictionary *attributes = (__bridge_transfer NSDictionary *)attributesRef;
        NSMutableDictionary *valueQuery = [NSMutableDictionary dictionaryWithDictionary:attributes];

        [valueQuery setObject:(__bridge id)kSecClassGenericPassword  forKey:(__bridge id)kSecClass];
        [valueQuery setObject:(__bridge id)kCFBooleanTrue            forKey:(__bridge id)kSecReturnData];

        CFTypeRef passwordDataRef = NULL;
        OSStatus result = SecItemCopyMatching((__bridge CFDictionaryRef)valueQuery, &passwordDataRef);
        if (result == noErr) {
            NSData *passwordData = (__bridge_transfer NSData *)passwordDataRef;
            uuidString = [[NSString alloc] initWithBytes:[passwordData bytes]
                                                  length:[passwordData length]
                                                encoding:NSUTF8StringEncoding];
        }
    }
}

// Failed to read the UUID from the KeyChain, so create a new UUID and store it
if (uuidString == nil || uuidString.length == 0) {
    // Generate the new UIID
    CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
    uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(kCFAllocatorDefault, uuidRef);
    CFRelease(uuidRef);

    // Now store it in the KeyChain
    NSDictionary *query = @{    (__bridge id)kSecClass:             (__bridge id)kSecClassGenericPassword,
                                (__bridge id)kSecAttrAccount:       kKeyChainVendorID,
                                (__bridge id)kSecAttrService:       kKeyChainVendorID,
                                (__bridge id)kSecAttrAccessGroup:   kKeyChainVendorIDAccessGroup,
                                (__bridge id)kSecAttrLabel:         @"",
                                (__bridge id)kSecAttrDescription:   @"",
                                (__bridge id)kSecAttrAccessible:    (__bridge id)kSecAttrAccessibleAfterFirstUnlock,
                                (__bridge id)kSecValueData:         [uuidString dataUsingEncoding:NSUTF8StringEncoding]
                            };

    OSStatus result = SecItemAdd((__bridge CFDictionaryRef)query, NULL);
    if (result != noErr) {
        NSLog(@"ERROR: Couldn't add to the Keychain. Result = %ld; Query = %@", result, query);
        return nil;
    }
}

// Save UUID to NSUserDefaults so that we can avoid the KeyChain next time
if (vendorIDMissingFromUserDefaults) {
    [[NSUserDefaults standardUserDefaults] setObject:uuidString forKey:kKeyChainVendorIDGroup];
}

return [[NSUUID alloc] initWithUUIDString:uuidString];

}

But i want to Know that here What is kKeyChainVendorID and kKeyChainVendorIDAccessGroup here it use is like as

 static NSString * const kKeyChainVendorID = @"co.cwbrn.PersistentIdentifier";
static NSString * const kKeyChainVendorIDAccessGroup = @"<AppIdentifier>.<keychain-access-group-identifier>";

For My application how i Get two Value like as kKeyChainVendorID and kKeyChainVendorIDAccessGroup??Please Give me Solution for that and in my Xcode 5.0 Version error are Occurred in line

 NSString *uuidString = [[NSUserDefaults standardUserDefaults] stringForKey:kKeyChainVendorIDGroup];

Erro is:- Replace kKeyChainVendorIDGroup with kKeyChainVendorID. Can i replace it then it is Work or not Please Give me Solution For my Both Question

Thanks in advance. and thanks to nelico that post answer in stack overflow.


Solution

  • Here i Post My Own Answer. I get answer From this Link

    http://objectivecwithsuraj.blogspot.in/2014/01/unique-identifier-uuid-ios.html
    

    i use FDKeyChain and Write Following Code to Save UUID In KeyChain

    Just Define Two String like as

    static NSString * const KeychainItem_Service = @"FDKeychain";
    static NSString * const KeychainItem_UUID = @"Local";
    

    and For Get UUID I write as

    uniqueIdentifier=[self generateUUID];
    -(NSString *)generateUUID {
    NSString *CFUUID = nil;
    
    if (![FDKeychain itemForKey: KeychainItem_UUID
                     forService: KeychainItem_Service
                          error: nil]) {
        CFUUIDRef uuid = CFUUIDCreate(kCFAllocatorDefault);
    
        CFUUID = (NSString *)CFBridgingRelease(CFUUIDCreateString(kCFAllocatorDefault, uuid));
    
        [FDKeychain saveItem: CFUUID
                      forKey: KeychainItem_UUID
                  forService: KeychainItem_Service
                       error: nil];
    
    } else {
        CFUUID = [FDKeychain itemForKey: KeychainItem_UUID
                             forService: KeychainItem_Service
                                  error: nil];
    }
    
    return CFUUID;
    

    }

    Hope it Help to SomeOne. and if i do some fault in my answer then please give me solution. Thanks For reply.