What to use if not "IPHONE UDID"? - iphone

Wow... look at all the "panic stories" online this week regarding using an iPhone's UDID.
[[UIDevice currentDevice] uniqueIdentifier]
What SHOULD we be using instead?
What if the phone is sold to another user... and an app has stored some data on a remote server, based on the phone's UDID?
(Of course, I want to avoid the problems with the app store's "encryption restrictions".)

Why not use the Mac Address and possibly then hash it up.
There is an excellent UIDevice-Extension Category here
- (NSString *) macaddress
{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
// NSString *outstring = [NSString stringWithFormat:#"%02X%02X%02X%02X%02X%02X",
// *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}
You could possibly hash this with the model?

As I asked this morning in this post, there are some alternative :
1- first, as Apple recommands, identify per install instead of indentifying per device.
Therefore, you can use CFUUIDRef. Example :
NSString *uuid = nil;
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID) {
uuid = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID));
[uuid autorelease];
CFRelease(theUUID);
}
2- If you care about a worldwide unique identifier, so you could store this identifier on iCloud.
3- At last, if you really need an identifier that remains after app re-install (that not occurs so frequently), you can use Keychains (Apple's keychain doc).
But will apple team like it ?

UUID is just depreciated and so will be around for a while, Apple have not said much about this depreciation much yet, I would wait until they have more to say about this and maybe the will offer some alternative.

Like this:
#interface UIDevice (UIDeviceAppIdentifier)
#property (readonly) NSString *deviceApplicationIdentifier;
#end
#implementation UIDevice (UIDeviceAppIdentifier)
- (NSString *) deviceApplicationIdentifier
{
static NSString *name = #"theDeviceApplicationIdentifier";
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString *value = [defaults objectForKey: name];
if (!value)
{
value = (NSString *) CFUUIDCreateString (NULL, CFUUIDCreate(NULL));
[defaults setObject: value forKey: name];
[defaults synchronize];
}
return value;
}
#end
the iOS documentation more or less describes use of CFUUIDCreate() to create an identifier and suggests using UserDefaults to store it.

The recommended way is by using UUID generation, and associate that with something that the user him/herself is willing to provide to the app.
Then, store this data externally, where it could be retrieved again. There are probably other ways to do this easily, but this is the recommended way.

One solution would be to have the application issue a free in-app purchase.
This purchase would be:
Trackable, with a unique number (purchase) number which would be meaningful only to your app.
Movable, if the person switches devices
Retrievable, if the app is deleted (or the phone is wiped and reloaded) - the In-App purchases can be restored.

Apple's documentation says:
"Do not use the uniqueIdentifier property. 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 class."
Here's a quick snippet:
CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);

Related

Id UUID static over sessions?

I want to use an alternative to the UDID and found this:
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
but in the simulator the method gives me different results every session?
Is this only in simulator?
I need to be sure that on actual devices the method returns me always the same string
to identify a user.
Is it true or not?
Mirza
CFUUIDRef will create different values at each session.
Solution 1:
Save the value in NSUserDefaults and next time onwards use it from the NSUserDefaults.
Solution 2:
You can use identifierForVendor for doing this.
NSString *udidVendor = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
According to UIDevice Class Reference:
The value of this property is the same for apps that come from the
same vendor running on the same device. A different value is returned
for apps on the same device that come from different vendors, and for
apps on different devices regardless of vendor.
Please check Unique Identifier In iOS 6
CFUUIDCreate gives you a Universally Unique Identifier every time you call that function, so each time you will get a different result (by definition).
What you can do is persist this in between sessions using, for example, NSUserDefaults, to uniquely identify a particular user (or bunch of user's settings).
CFUUID is not persisted at all.
Every time you call CFUUIDCreate the system will return to you a brand new unique identifier.
If you want to persist this identifier you will need to do that yourself using NSUserDefaults, Keychain, Pasteboard or some other means.
Read the code one line at a time and try to understand what it does. The CFUUIDCreate function creates a new UUID every time you call it. That would explain your finding. You need to save the value in NSUserDefaults* the first time and use that value the next time you launch the app:
+ (NSString *)GetUUID
{
NSString *string = [[NSUserDefaults standardUserDefaults] objectForKey: #"UUID"];
if (!string)
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
string = (NSString*)[CFUUIDCreateString(NULL, theUUID) autorelease];
CFRelease(theUUID);
[[NSUserDefaults standardUserDefaults] setObject: string forKey: #"UUID"];
}
return string;
}
*There are one small caveat of using NSUserDefaults - UUID will be created again if user uninstalls and reinstalls the app again. If you can't live with this, look into saving it in Keychain. Alternatively, you might want to look at OpenUDID.
The method will always return a unique string. If the app will only ever have a single user, run this method once when the user first launches the app and persist that string in a plist, or NSUserDefaults, or core data if you've already using it.
The link below may help with this UUID persistence logic:
UUID for app on iOS5
However, if the user then uninstalls and reinstalls the app, this persisted UUID will still be lost and need will be generated again.
Device IDs are also no longer allowed by Apple.
Assuming the UUID is required because the app connects to a server, as far as I know, you need the user log in to the server with a user name and password.
It is always different. UUID includes timestamps, so every time you call this function, you will get a different (random) one.
I have followed this approach in IDManager class,
This is a collection from different solutions. KeyChainUtil is a wrapper to read from keychain. A similar keychain util is found in github.
// IDManager.m
/*
A replacement for deprecated uniqueIdentifier API. Apple restrict using this from 1st May, 2013.
We have to consider,
* iOS <6 have not the ASIIdentifer API
* When the user upgrade from iOS < 6 to >6
- Check if there is a UUID already stored in keychain. Then use that.
- In that case, this UUID is constant for whole device lifetime. Keychain item is not deleted with application deletion.
*/
#import "IDManager.h"
#import "KeychainUtils.h"
#import "CommonUtil.h"
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
#import <AdSupport/AdSupport.h>
#endif
#include <sys/socket.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>
/* Apple confirmed this bug in their system in response to a Technical Support Incident request. They said that identifierForVendor and advertisingIdentifier sometimes returning all zeros can be seen both in development builds and apps downloaded over the air from the App Store. They have no work around and can't say when the problem will be fixed. */
#define kBuggyASIID #"00000000-0000-0000-0000-000000000000"
#pragma mark
#pragma mark
#implementation IDManager
+ (NSString *) getUniqueID {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
if (NSClassFromString(#"ASIdentifierManager")) {
NSString * asiID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
if ([asiID compare:kBuggyASIID] == NSOrderedSame) {
NSLog(#"Error: This device return buggy advertisingIdentifier.");
return [IDManager getUniqueUUID];
} else {
return asiID;
}
} else {
#endif
return [IDManager getUniqueUUID];
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 60000
}
#endif
}
+ (NSString *) getUniqueUUID
{
NSError * error;
NSString * uuid = [KeychainUtils getPasswordForUsername:#"UserName" andServiceName:#"YourServiceName" error:&error];
if (error) {
NSLog(#"Error geting unique UUID for this device! %#", [error localizedDescription]);
return nil;
}
if (!uuid) {
DLog(#"No UUID found. Creating a new one.");
uuid = [IDManager getUUID];
uuid = [CommonUtil md5String:uuid]; // create md5 hash for security reason
[KeychainUtils storeUsername:#"UserName" andPassword:uuid forServiceName:#"YourServiceName" updateExisting:YES error:&error];
if (error) {
NSLog(#"Error geting unique UUID for this device! %#", [error localizedDescription]);
return nil;
}
}
return uuid;
}
+ (NSString *) readUUIDFromKeyChain {
NSError * error;
NSString * uuid = [KeychainUtils getPasswordForUsername:#"UserName" andServiceName:#"YourServiceName" error:&error];
if (error) {
NSLog(#"Error geting unique UUID for this device! %#", [error localizedDescription]);
return nil;
}
return uuid;
}
/* NSUUID is after iOS 6. So we are using CFUUID for compatibility with iOS 4.3 */
+ (NSString *)getUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
#pragma mark - MAC address
/* THIS WILL NOT WORK IN iOS 7. IT WILL RETURN A CONSTANT MAC ADDRESS ALL THE TIME.
SEE - https://developer.apple.com/news/?id=8222013a
*/
// Return the local MAC address
// Courtesy of FreeBSD hackers email list
// Last fallback for unique identifier
+ (NSString *) getMACAddress
{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Error: Memory allocation error\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2\n");
free(buf); // Thanks, Remy "Psy" Demerest
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}
+ (NSString *) getHashedMACAddress
{
NSString * mac = [IDManager getMACAddress];
return [CommonUtil md5String:mac];
}
#end

how to get device udid in iphone sdk?

I developing iPhone application. In this app i need to get device udid. In simulator working fine, but in iphone device not getting correct value, the values getting 0.
The code are following;
UIDevice *device = [UIDevice currentDevice];
NSString *uniqueIdentifier = [device uniqueIdentifier];
Thanks,
As we know uniqueIdentifier is deprecated in iOS 5.0 so docs recommend you to use CFUUID
instead. You can get CFUUID using
CFUUIDRef uuidRef = CFUUIDCreate(kCFAllocatorDefault);
NSString *uuidString = (NSString *)CFUUIDCreateString(NULL,uuidRef);
CFRelease(uuidRef);
Please save the uuidString in user defaults or in other place because you can not generate the same uuidString again.
You can use mac address also in place of this as an alternative how-can-i-programmatically-get-the-mac-address-of-an-iphone
Hope it helps you.
UDID is deprecated. From 1st May 2013, Apple is not approving any app that access uniqueIdentifier. Instead you can use ASIIDentifier or NSUUID.Or MAC address.
I have followed this approach in IDManager class,
This is a collection from different solutions. KeyChainUtil is a wrapper to read from keychain.
#define kBuggyASIID #"00000000-0000-0000-0000-000000000000"
+ (NSString *) getUniqueID {
if (NSClassFromString(#"ASIdentifierManager")) {
NSString * asiID = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
if ([asiID compare:kBuggyASIID] == NSOrderedSame) {
NSLog(#"Error: This device return buggy advertisingIdentifier.");
return [IDManager getUniqueID];
} else {
return asiID;
}
} else {
return [IDManager getUniqueUUID];
}
}
+ (NSString *) getUniqueUUID {
NSError * error;
NSString * uuid = [KeychainUtils getPasswordForUsername:kBuyassUser andServiceName:kIdOgBetilngService error:&error];
if (error) {
NSLog(#"Error geting unique UUID for this device! %#", [error localizedDescription]);
return nil;
}
if (!uuid) {
DLog(#"No UUID found. Creating a new one.");
uuid = [IDManager GetUUID];
uuid = [Util md5String:uuid];
[KeychainUtils storeUsername:kBuyassUser andPassword:uuid forServiceName:kIdOgBetilngService updateExisting:YES error:&error];
if (error) {
NSLog(#"Error geting unique UUID for this device! %#", [error localizedDescription]);
return nil;
}
}
return uuid;
}
/* NSUUID is after iOS 6. */
+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return [(NSString *)string autorelease];
}
#pragma mark - MAC address
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Last fallback for unique identifier
+ (NSString *) getMACAddress
{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Error: Memory allocation error\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2\n");
free(buf); // Thanks, Remy "Psy" Demerest
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}

Issue with Enterprise build and UUID usage

As you know Apple recently deprecated the usage of UDID. So my solution to this was
Generate CFUUID
Save it to keychain
Re-access the keychain item there after.
This has been working good. But, for some reason we recently saw that with the installation of an enterprise build we are getting a different UUID(Which was supposed to be stored on keychain with our unique access key).
Did any one come across such situation? Here is the code to create the UUID and store it onto keychain..
+ (NSString *)registerUUIDWithKeyChain
{
CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *uuidString = (NSString *) CFUUIDCreateString(NULL, udid);
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:#"UniqueApp" accessGroup:nil];
NSString *userName = #"UniqueAppName";
NSString *password = uuidString;
[keychainItem setObject:userName forKey:(id)kSecAttrAccount];
[keychainItem setObject:password forKey:(id)kSecValueData];
[keychainItem release];
return uuidString;
}
+ (NSString *)userUUID
{
KeychainItemWrapper *keychainItem = [[KeychainItemWrapper alloc] initWithIdentifier:#"UniqueApp" accessGroup:nil];
//Accesing the v_data was the only way. For some reason there is a runtime issue if we try to access it though "kSecValueData"
NSString *uuid = [keychainItem.keychainItemData objectForKey:#"v_Data"];
//Check if the app is installed for the first time on the device. If YES register the UUID in to the keychain.
//Also check if it is a reinstall by accessing the previous keyChainItem with our Identifier.
if ([[[NSUserDefaults standardUserDefaults] valueForKey:#"firstRun"] intValue] == 0 && !(uuid.length > 0))
{
uuid = [UIDevice_Additions registerUUIDWithKeyChain];
NSLog(#"\n First Time Registered UUID is %#", uuid);
//after stuff done
[[NSUserDefaults standardUserDefaults] setValue:[NSNumber numberWithInt:1] forKey:#"firstRun"];
[[NSUserDefaults standardUserDefaults] synchronize];
[keychainItem release];
return uuid;
}
[keychainItem release];
return uuid;
}
#end
Okie,
After battling with the issue for a day, I found what was triggering this.
Keychain's are certificate dependent
An enterprise build is created with a different certificate
Hence, when the code tries to access your key from an enterprise build you will not find it and hence the code generates will generate a new one.
Solution would be to create your Keychain so that it is globally accessible. You can change the accessGroup variable in the KeyChainWrapper init method.
Good Luck!
you may use MAC Addres instread of UUID
- (NSString *) macaddress
{
int mib[6];
size_t len;
char *buf;
unsigned char *ptr;
struct if_msghdr *ifm;
struct sockaddr_dl *sdl;
mib[0] = CTL_NET;
mib[1] = AF_ROUTE;
mib[2] = 0;
mib[3] = AF_LINK;
mib[4] = NET_RT_IFLIST;
if ((mib[5] = if_nametoindex("en0")) == 0) {
printf("Error: if_nametoindex error\n");
return NULL;
}
if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 1\n");
return NULL;
}
if ((buf = malloc(len)) == NULL) {
printf("Could not allocate memory. error!\n");
return NULL;
}
if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
printf("Error: sysctl, take 2");
return NULL;
}
ifm = (struct if_msghdr *)buf;
sdl = (struct sockaddr_dl *)(ifm + 1);
ptr = (unsigned char *)LLADDR(sdl);
NSString *outstring = [NSString stringWithFormat:#"%02X:%02X:%02X:%02X:%02X:%02X",
*ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
free(buf);
return outstring;
}

Create an unique identifier for iOS devices?

Is possible to discover the iOS device identifier, using Xcode. I need to each app downloaded have a unique identifier. I thought in generate random numbers, but they might generate the same number more than once! Anyone have an idea?
In UIDevice class apple has provided method uniqueIdentifier but now its deprecated(for iOS5), In method's documentation you will find how you can use uniqueIdentifier.
I've found a pretty simple way to do this, here's how:
Press COMMAND + N and select Cocoa Touch Class.
Name your class NSString+UUID and hit next.
Then, replace the code in NSString+UUID.h with:
#interface NSString (UUID)
+ (NSString *)uuid;
#end
And in NSString+UUID.m with:
#implementation NSString (UUID)
+ (NSString *)uuid {
NSString *uuidString = nil;
CFUUIDRef uuid = CFUUIDCreate(NULL);
if (uuid) {
uuidString = (NSString *)CFUUIDCreateString(NULL, uuid);
CFRelease(uuid);
}
return [uuidString autorelease];
}
#end
Now, when you need to get the UUID (i.e: store it using NSUserDefaults when your app loads):
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
NSString *userIdentifierKey = #"user-identifier"
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:userIdentifierKey] == nil) {
NSString *theUUID = [NSString uuid];
[defaults setObject:theUUID forKey:userIdentifierKey];
[defaults synchronize];
}
// additional application setup...
return YES;
}
Try this UIDevice-with-UniqueIdentifier-for-iOS-5, it uses the device's mac address as unique identifier.
iOS6 provides a new replacement [[[UIDevice currentDevice] identifierForVendor] UUIDString]
The value of this property is the same for apps that come from the
same vendor running on the same device. A different value is returned
for apps onthe same device that come from different vendors, and for
apps on different devices regardles of vendor.
See: https://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIDevice_Class/Reference/UIDevice.html#//apple_ref/doc/uid/TP40006902-CH3-SW49
You can create a category of UIApplication , UIDevice or as you prefere like this (ARC example)
#interface UIApplication (utilities)
- (NSString*)getUUID;
#end
#implementation UIApplication (utilities)
- (NSString*)getUUID {
NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
static NSString *uuid = nil;
// try to get the NSUserDefault identifier if exist
if (uuid == nil) {
uuid = [standardUserDefault objectForKey:#"UniversalUniqueIdentifier"];
}
// if there is not NSUserDefault identifier generate one and store it
if (uuid == nil) {
uuid = UUID ();
[standardUserDefault setObject:uuid forKey:#"UniversalUniqueIdentifier"];
[standardUserDefault synchronize];
}
return uuid;
}
#end
UUID () is this function
NSString* UUID () {
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return (__bridge NSString *)uuidStringRef;
}
this generate an unique identifier stored into the NSUserDefault to be reused whenever the application need it - This identifier will unique related to the application installs not to the device, but can be used for example to take trace about the number devices subscribed the APN service etc...
After that you can use it in this way:
NSString *uuid = [[UIApplication sharedApplication] getUUID];
try this
- (NSString *)getDeviceID
{
NSString *uuid = [self gettingString:#"uniqueAppId"];
if(uuid==nil || [uuid isEqualToString:#""])
{
CFUUIDRef theUUID = CFUUIDCreate(kCFAllocatorDefault);
if (theUUID)
{
uuid = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, theUUID));
[self savingString:#"uniqueAppId" data:uuid];
[uuid autorelease];
CFRelease(theUUID);
}
}
return uuid;
// this is depreciated
// UIDevice *device = [UIDevice currentDevice];
// return [device uniqueIdentifier];
}
Use this: [[UIDevice currentDevice] identifierForVendor]
For more information take a look to this answer

How to generate a unique identifier?

I need to generate some int value that would never repeat (at least theoretically). I know there is arc4random() fnc but I'm not sure how to use it with some current date or smth :(
This returns a unique key very similar to UUID generated in MySQL.
+ (NSString *)uuid
{
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return [(NSString *)uuidStringRef autorelease];
}
ARC version:
+ (NSString *)uuid
{
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return (__bridge_transfer NSString *)uuidStringRef;
}
A simple version to generate UUID (iOS 6 or later).
Objective-C:
NSString *UUID = [[NSUUID UUID] UUIDString];
Swift 3+:
let uuid = UUID().uuidString
It will generate something like 68753A44-4D6F-1226-9C60-0050E4C00067, which is unique every time you call this function, even across multiple devices and locations.
Reference:
https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSUUID_Class/Reference/Reference.html
If you are using CoreData to save the played games, NSManagedObject's objectID should serve your purpose without any extra effort.
You can use the time in milliseconds or a more advanced way GUID.
You can create a category of UIApplication , UIDevice or as you prefere like this (ARC example)
#interface UIApplication (utilities)
- (NSString*)getUUID;
#end
#implementation UIApplication (utilities)
- (NSString*)getUUID {
NSUserDefaults *standardUserDefault = [NSUserDefaults standardUserDefaults];
static NSString *uuid = nil;
// try to get the NSUserDefault identifier if exist
if (uuid == nil) {
uuid = [standardUserDefault objectForKey:#"UniversalUniqueIdentifier"];
}
// if there is not NSUserDefault identifier generate one and store it
if (uuid == nil) {
uuid = UUID ();
[standardUserDefault setObject:uuid forKey:#"UniversalUniqueIdentifier"];
[standardUserDefault synchronize];
}
return uuid;
}
#end
UUID () is this function
NSString* UUID () {
CFUUIDRef uuidRef = CFUUIDCreate(NULL);
CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef);
CFRelease(uuidRef);
return (__bridge NSString *)uuidStringRef;
}
this generate an unique identifier stored into the NSUserDefault to be reused whenever the application need it - This identifier will unique related to the application installs not to the device, but can be used for example to take trace about the number devices subscribed the APN service etc...
After that you can use it in this way:
NSString *uuid = [[UIApplication sharedApplication] getUUID];
A simple timestamp (milliseconds * 10) should do the trick:
self.uid = [NSNumber numberWithInteger:[NSDate timeIntervalSinceReferenceDate] * 10000];
You did not say it must be random. So why not start with some number, and then just add by 1 to the last number you generated.
This method should give you at lest 4 billion unique numbers to start with:
-(NSInteger)nextIdentifies;
{
static NSString* lastID = #"lastID";
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
NSInteger identifier = [defaults integerForKey:lastID] + 1;
[defaults setInteger:identifier forKey:lastID];
[defaults synchronize];
return identifier;
}
If you have a NSDictionary, you could generate a progressive id from the last item:
NSInteger maxKey = -1;
for(NSString *key in [YOUR_DICTIONARY allKeys])
{
NSInteger intKey = [key integerValue];
if(intKey > maxKey)
{
maxKey = intKey;
}
}
NSString *newKey = [NSString stringWithFormat:#"%d", maxKey + 1];
You have to be careful, especially if you use the increment by 1 routines, that if your app is deleted and reloaded on the iDevice, that you won't have your saved default number anymore. It will start over from the beginning. If you're storing user's scores, you might want to save their highest number too. Better to check the time routines for seconds (or milliseconds) after a certain date. The GUID mentioned above is good too, if you need that kind of uniqueness.