简体   繁体   中英

Swift UserDefaults.standard.register in AppDelegate didFinishLaunchingWithOptions is not working

I am attempting to register a Standard UserDefault value in AppDelegate but getting nil when I try to get the value out in a ViewController. I did this all of time in Obj C. What am I missing with the Swift code here? Thanks

AppDelegate

 private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    setupAppearance()
    
    // register default values for userDefaults
    UserDefaults.standard.register(defaults: [
           "selectedUUID": "0"
            ])
    UserDefaults.standard.synchronize().  // is this still needed?
    
    
    
    return true
}

ViewController

 override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    
    
    // Get the uuid that was registered in AppDelegate
    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    var defaults: UserDefaults = UserDefaults.standard
    var selectedUUID = defaults.string(forKey: "selectedUUID")

    
    print(selectedUUID!)  // selectedUUID is nil, why?    }

You can use UserDefaults.standard.set to set the User Default value. There is no need to call synchronize, according to Apple here :

Waits for any pending asynchronous updates to the defaults database and returns; this method is unnecessary and shouldn't be used .

This was deprecated in iOS 12 ( release notes ).

Try placing the following code in your didFinishLaunchingWithOptions to see this work:

let testDefaults = UserDefaults.standard.object(forKey: "selectedUUID") as? String

if testDefaults != nil {

    print("Found UUID")

} else {

    print("Did Not Find UUID")
    UserDefaults.standard.set(UUID().uuidString, forKey: "selectedUUID")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM