user8188972
user8188972

Reputation:

New UUID generated on each run

I have this code in my viewDidLoad:

let udid = UUID().uuidString

But each time I run the application I get a new generated UUID. How come?

I need the same ID for each user to be able to identify them so should I save this in a UserDefault or how should I do to uniquely identify a user even when the user restarts the application?

Upvotes: 1

Views: 1811

Answers (5)

FontFamily
FontFamily

Reputation: 386

@State private var uuid: String = {
    UserDefaults.standard.register(defaults: ["uuid" : UUID().uuidString])
    return UserDefaults.standard.string(forKey: "uuid") ?? ""
}()
{
    didSet {UserDefaults.standard.set(uuid, forKey: "uuid")}
}

The code above will help you do this in SwiftUI. It checks to see whether the string is already registered. If not, it assigns a UUID to it. The UUID will stay the same unless the app is deleted and reinstalled.

This generates a random UUID, not a device identifier. The other answer accepted above will return the device identifier.

Upvotes: 0

Codetard
Codetard

Reputation: 2595

This is the way to go!

func getUUID() -> String {
    let userDefaults = UserDefaults.standard
    
    if (userDefaults.string(forKey: "uuid") ?? "").isEmpty == true {
        userDefaults.set(UUID().uuidString,forKey: "uuid")
        userDefaults.synchronize()
        return userDefaults.string(forKey: "uuid") ?? ""
    } else {
        return userDefaults.string(forKey: "uuid") ?? ""

    }
}

Upvotes: 0

Ester Kaufman
Ester Kaufman

Reputation: 868

Save the generated UUID in application settings. When uninstall, its will be removed.

Upvotes: 0

Rob Napier
Rob Napier

Reputation: 299265

The tool for what you're trying to do is UIDevice.current.identifierForVendor. This returns exactly the kind of UUID you're describing (and is intended for this purpose).

Upvotes: 2

Liubo
Liubo

Reputation: 703

According to UUID documentation:

init() Initializes a new UUID with RFC 4122 version 4 random bytes.

var uuidString: String Returns a string created from the UUID, such as “E621E1F8-C36C-495A-93FC-0C247A3E6E5F”

So every time when you're calling let udid = UUID().uuidString, it returns the new UUID. If you need to have the same UUID, just save it and read next time when you'll need it. E.g:

UserDefaults.standard.set(udid, forKey: "MY_UUID")

and next time check the UserDefaults for the value and create one if needed:

if let udid = UserDefaults.standard.value(forKey: "MY_UUID") as? String, !udid.isEmpty {
     // Use it...
} else {
    let udid = UUID().uuidString
    UserDefaults.standard.set(udid, forKey: "MY_UUID")
}

But, please, be aware that UserDefaults are cleared on app uninstall. So you can use Keychain to save UUID if you need to have access to if after re-install. Also, you can use libs, like FCUUID

Upvotes: 0

Related Questions