how to retrieve user setting in iOS? [Xcode 7 + Swift 2]

604 Views Asked by At

I am using Xcode 7 + Swift 2.

I added a setting.bundle to the root of my app with a single text field.

Root.plist looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>StringsTable</key>
    <string>Root</string>
    <key>PreferenceSpecifiers</key>
    <array>
        <dict>
            <key>Type</key>
            <string>PSGroupSpecifier</string>
            <key>Title</key>
            <string>Controller Settings:</string>
        </dict>
        <dict>
            <key>Type</key>
            <string>PSTextFieldSpecifier</string>
            <key>Title</key>
            <string>Enter Text</string>
            <key>Key</key>
            <string>key</string>
            <key>DefaultValue</key>
            <string>Text</string>
            <key>IsSecure</key>
            <false/>
            <key>KeyboardType</key>
            <string>NumbersAndPunctuation</string>
            <key>AutocapitalizationType</key>
            <string>None</string>
            <key>AutocorrectionType</key>
            <string>No</string>
        </dict>
    </array>
</dict>
</plist>

I then try to:

  1. Read the default value ("Text")
  2. Change the text field in the iOS settings and then read the new String.

I used this two lines of code:

let settings = NSUserDefaults.standardUserDefaults()
let setting_value = settings.stringForKey("key")! as String

but all i get is this error and the app would not continue:

fatal error: unexpectedly found nil while unwrapping an Optional value

all I want is to read the setting and display the String to a label.

Thanks.

EDIT: I Understand now that the error is because the value in not assigned yet. to prevent the error I put 'if' before:

if let name = settings.stringForKey("key") {
     print(name)
   }

but how can I actually read the value inside "key"?

0

There are 0 best solutions below