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?
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!)