Thursday, July 26, 2012

IPhone: Solution for [[UIDevice currentDevice] uniqueIdentifier]]


[[UIDevice currentDevice] uniqueIdentifier] is deprecated in iOS5

APPLE DOCUMENTATION:
To create a unique identifier specific to your app, you can call the CFUUIDCreate function to create a UUID, and write it to the defaults database using the NSUserDefaults
/*
 * Generates UUID using CFUUIDCreate
 */
- (NSString *) generateUUID
{
    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);
    
    return result;
}

// Use the Below Code to save the UUID into the NSUserDefaults, so that we can use, anywhere in the application.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *fetchUUID = [defaults objectForKey:@"UUID"];
if (fetchedUUID == nil || [fetchedUUID isEqualToString:@""])
{
     NSLog(@"Checking in if");
     [defaults setObject:[self generateUUID] forKey:@"UUID"];
}    
fetchUUID = [defaults objectForKey:@"UUID"];

Use the above code to get UUID in iOS5.