简体   繁体   中英

swift Xcode reading application settings

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) 捆绑设置

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.

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