2

I am new to swift/ios programming. I created a small app with settings but I can't seem to read value.

        UserDefaults.standard.register(defaults: [String : Any]())

    let settings = UserDefaults.standard;

    let k = Bundle.main.infoDictionary!;

    let b = settings.dictionaryRepresentation()

  let val3 = Bundle.main.object(forInfoDictionaryKey: "digit_preference")


    let value2 = settings.string(forKey: "digit_preference")

I can't find my settings "digit_preference" in Bundle.main.InfoDictionary or UserDefaults.standard.dictionaryRepresentation()

I can view my application settings properly in my phone. (Digits set to 2) Bundle.settings

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Nite
  • 443
  • 1
  • 6
  • 11
  • just for clarification, i get "nil" when I try to access value (variable val3, value2 above) – Nite Nov 16 '17 at 04:01
  • You're using "digit_preference" as a key to access the value, but I don't see such a key in your `plist`, it is a string value whose key is "Identifier". Also that key/value pair is inside a Dictionary which is inside a "Preference items" array, so you need to first get that element of the array and then get the value. – Au Ris Nov 16 '17 at 06:22

1 Answers1

0

You need to cast the file data to a dictionary at first since the root structure is a Dictionary. This of course, if the file you're showing us is actually a .plist file; the following is how to access a .plist file, but the first step is also common for almost every other file type in your app bundle. What differs (say from .txt, .json, etc) is the second step depending on what you want to do..

Like so:

guard let idForResource = Bundle.main.path(forResource: "pListFilename", ofType: ".plist"), 
       let dict = NSDictionary(contentsOfFile: idForResource) as? [String: Any] else { 
      return }

Then you access the variable through dict like you would from any other dictionary.

jlmurph
  • 1,050
  • 8
  • 17