iOS14 UserDefaults empty or not found

A few of my users upgraded to iOS 14 recently and my app fell over on startup.

I've fixed the initial problem with attempting to load UserDefaults into text fields (optionals) but every time I run the app on the iPhone or the simulator, the UserDefaults have no data. It behaves as if it can't find the correct UserDefault file.

I've interrogated UserDefaults in debug and it is empty (see below). I've printed the defaults and I get keys and some data as per settings but saving is not working because the next time I run the app, the data is empty.

Printing description of defaults:<NSUserDefaults: 0x6000014213b0>
Printing description of defaults._container_:<nil>
Printing description of defaults._identifier_:kCFPreferencesCurrentApplication
Printing description of defaults._kvo_:<nil>
Printing description of *(defaults._kvo_):(id) [0] = <parent is NULL>

Printing description of defaults:
(NSObject) baseNSObject@0 = {
  isa = NSUserDefaults

Did anyone else have a similar problem?

Example code:

Set UserDefault

let defaults = UserDefaults.standard

defaults.set(yourName, forKey: "userName")

Get UserDefault

let defaults = UserDefaults.standard

let yourFirstName = defaults.string(forKey: "userName")

plist file name

I used the following code to find where the simulator plist file is and it returned com.myAppName.App.plist! I opened it and it only contained a few settings, not all of them. So why is the extension .App.plist??

let libraryPath = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]

Okay, now I've found that its using my bundle identifier and that's why it has .App.plist. All good but why are many of the settings missing compared to root.plist in the project under Settings.bundle? There are 28 items in root.plist and only 14 in the com.myAppName.App.plist.

Read more here:

Content Attribution

This content was originally published by Sue Southcott at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: