How to Generate Uuid in iOS

How to create a GUID/UUID using iOS

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

EDIT: -[UIDevice uniqueIdentifier] is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.

If you need to create several UUID, just use this method (with ARC):

+ (NSString *)GetUUID
{
CFUUIDRef theUUID = CFUUIDCreate(NULL);
CFStringRef string = CFUUIDCreateString(NULL, theUUID);
CFRelease(theUUID);
return (__bridge NSString *)string;
}

EDIT: Jan, 29 2014:
If you're targeting iOS 6 or later, you can now use the much simpler method:

NSString *UUID = [[NSUUID UUID] UUIDString];

Generate a UUID on iOS from Swift

Try this one:

let uuid = NSUUID().uuidString
print(uuid)

Swift 3/4/5

let uuid = UUID().uuidString
print(uuid)

How to generate UUID in ios

Try:

CFUUIDRef udid = CFUUIDCreate(NULL);
NSString *udidString = (NSString *) CFUUIDCreateString(NULL, udid);

UPDATE:

As of iOS 6, there is an easier way to generate UUID. And as usual, there are multiple ways to do it:

Create a UUID string:

NSString *uuid = [[NSUUID UUID] UUIDString];

Create a UUID:

[NSUUID UUID]; // which is the same as..
[[NSUUID] alloc] init];

Creates an object of type NSConcreteUUID and can be easily casted to NSString, and looks like this: BE5BA3D0-971C-4418-9ECF-E2D1ABCB66BE

NOTE from the Documentation:

Note: The NSUUID class is not toll-free bridged with CoreFoundation’s CFUUIDRef. Use UUID strings to convert between CFUUID and NSUUID, if needed. Two NSUUID objects are not guaranteed to be comparable by pointer value (as CFUUIDRef is); use isEqual: to compare two NSUUID instances.

Objective-C generate UUID

The easiest way to get a UUID in Obj-C is to use the UUID class:

NSUUID *uuid = [NSUUID UUID];
NSString *str = [uuid UUIDString];

Generate UUID from name space?

The Swift standard library or the Foundation framework have no built-in method for version 5 UUIDs, as far as I know.

Here is a possible implementation for version 3 and version 5 UUIDs, taken from the description at Generating v5 UUID. What is name and namespace? and the reference implementation in RFC 4122.

(Updated for Swift 4 and later.)

import Foundation
import CommonCrypto

extension UUID {

enum UUIDVersion: Int {
case v3 = 3
case v5 = 5
}

enum UUIDv5NameSpace: String {
case dns = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"
case url = "6ba7b811-9dad-11d1-80b4-00c04fd430c8"
case oid = "6ba7b812-9dad-11d1-80b4-00c04fd430c8"
case x500 = "6ba7b814-9dad-11d1-80b4-00c04fd430c8"
}

init(version: UUIDVersion, name: String, nameSpace: UUIDv5NameSpace) {
// Get UUID bytes from name space:
var spaceUID = UUID(uuidString: nameSpace.rawValue)!.uuid
var data = withUnsafePointer(to: &spaceUID) { [count = MemoryLayout.size(ofValue: spaceUID)] in
Data(bytes: $0, count: count)
}

// Append name string in UTF-8 encoding:
data.append(contentsOf: name.utf8)

// Compute digest (MD5 or SHA1, depending on the version):
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH))
data.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Void in
switch version {
case .v3:
_ = CC_MD5(ptr.baseAddress, CC_LONG(data.count), &digest)
case .v5:
_ = CC_SHA1(ptr.baseAddress, CC_LONG(data.count), &digest)
}
}

// Set version bits:
digest[6] &= 0x0F
digest[6] |= UInt8(version.rawValue) << 4
// Set variant bits:
digest[8] &= 0x3F
digest[8] |= 0x80

// Create UUID from digest:
self = NSUUID(uuidBytes: digest) as UUID
}
}

Example 1 (Your case):

let uuid = UUID(version: .v5, name: "5a23dbfb2626b400190998fc-5pCAvA7h8k9JuErRn", nameSpace: .dns)
print(uuid) // 2522B097-8532-548E-A18B-9366C6511B5E

Example 2 (From Appendix B in RFC 4122, as corrected in the Errata):

let uuid = UUID(version: .v3, name: "www.widgets.com", nameSpace: .dns)
print(uuid) //3D813CBB-47FB-32BA-91DF-831E1593AC29

How to generate Unique ID of device for iPhone/iPad using Objective-c

Yes, UDID is deprecated; we are not allowed to get UDID due to user privacy purposes. Apple does not allow to get any identifiers that uniquely identifies a device, such as IMEI, MAC address, UDID etc.

UUID is the best way to go as of now. But that would be unique for each vendor. You are not assured that it will be unique each time you get the UUID string. Best bet is to store the UUID string to phone's Keychain and retrieve it when needed, with a catch. When you factory-reset your phone, the keychain items would be erased. This limitation should be kept in mind.


UPDATE - IN IOS 10.3 BETA'S:

It seems that Apple has made some changes to how Keychain works in iOS 10.3+. Keychain items stored in the Keychain will be deleted when the all the apps from the specific vendor are uninstalled. According to Apple, the residence of sensitive information of an app even after the app is gone from the device may lead to security risks, so they decided to forbid this kind of behavior.

Developers relying on Keychain storage even after an uninstall for their apps can make use of this WORKAROUND to continue with the intended functionality. According to this workaround, any app can access the information stored in that specific Keychain Access Group, so it is recommended that adding an extra layer of encryption to your data will protect it with even more security, although keychain encrypts items by default.


UPDATE - IOS 10.3.3 (STABLE):
It seems that the keychain items deletion was a BUG in early betas of iOS 10.3.3 and was fixed later in the stable release. This might have been caused during betas since strange things can happen during that phase. It should be no problem to use Keychain hereafter.

How to generate a unique identifier?

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;
}

Generate the same UUID from the same String

The official way to do this is with a version 5 UUID (RFC 4122 Section 4.3):

4.3 Algorithm for Creating a Name-Based UUID

The version 3 or 5 UUID is meant for generating UUIDs from "names"
that are drawn from, and unique within, some "name space".

The process is to hash your string, and then insert that into a UUID. I'm going to carefully follow the spec here, but I'll mark the parts you could ignore and it'll still work correctly.

As matt notes, you can just use a SHA directly if you just need a hash. But if your system actually requires a UUID, this is how you do it.

  • Define a namespace (this isn't fully necessary, but it will make sure your UUIDs are globally unique):
let namespace = "com.example.mygreatsystem:"
  • Combine that with your string
let inputString = "arandomstring"
let fullString = namespace + inputString
  • Hash the values. The UUID v5 spec specifically calls for SHA-1, but feel free to use SHA-256 (SHA-2) here instead. There's no actual security concern with using SHA-1 here, but it's good practice to move to SHA-2 whenever you can.
import CryptoKit

let hash = Insecure.SHA1.hash(data: Data(fullString.utf8)) // SHA-1 by spec

or

let hash = SHA256.hash(data: Data(fullString.utf8)) // SHA-2 is generally better
  • Take the top 128-bits of data. (It is safe to extract any subset of bits from a SHA-1 or SHA-2 hash. Each bit is "effectively random.")
var truncatedHash = Array(hash.prefix(16))
  • Correctly set the version and variant bits. This doesn't really matter for most uses. I've never encountered a system that actually parses the UUID metadata. But it's part of the spec. And if you use v4 random UUIDs for future records (which are the "normal" UUIDs for almost every system today), then this would allow you to distinguish which were created by hashing and which were random if that mattered for any reason. See UUIDTools for a nice visual introduction to the format.
truncatedHash[6] &= 0x0F    // Clear version field
truncatedHash[6] |= 0x50 // Set version to 5

truncatedHash[8] &= 0x3F // Clear variant field
truncatedHash[8] |= 0x80 // Set variant to DCE 1.1
  • And finally, compute your UUID:
let uuidString = NSUUID(uuidBytes: truncatedHash).uuidString


Related Topics



Leave a reply



Submit