Thursday, September 29, 2022

[FIXED] Why is UUID nil in simulator?

Issue

I'm developing a tvOS app fully with Swift.

In AppDelegate.swift, I try to print UUID under willFinishLaunchingWithOptions.

However, error message shows fatal error: unexpectedly found nil while unwrapping an Optional value.

The app was actually functional and worked well before. This bug happened after I reset the simulator.

Here is how I get UUID.

let UUIDValue = UIDevice.current.identifierForVendor!.uuidString
let newuuid = UserDefaults.standard.object(forKey: "uuid") as? String
print ("This device uuid is " + newuuid!) // error message happens here

I believe every device should contain a UUID, but how it happened?


Solution

You are trying to get newuuid from UserDefaults:

let newuuid = UserDefaults.standard.object(forKey: "uuid") as? String

but you have zero entries in UserDefaults after resetting the Simulator and did not set a value for key "uuid" yet.

This does not make much sense, but fixes the issue:

let uuidValue = UIDevice.current.identifierForVendor!.uuidString
UserDefaults.standard.setValue(uuidValue, forKey: "uuid") // add entry in UserDefaults
let newuuid = UserDefaults.standard.object(forKey: "uuid") as? String
print ("This device uuid is " + newuuid!)


Answered By - shallowThought
Answer Checked By - Timothy Miller (PHPFixing Admin)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.