Home > Articles > Mobile Application Development & Programming

This chapter is from the book

Recipe: Adding Custom Settings Bundles—Or Not

iOS uses the NSUserDefaults class to access and manage application preferences. With it, you can store information that your application needs to preserve between successive runs. For example, you might save a current player name, a list of high scores, or the last-used view configuration. User defaults programmatically assign values to a persistent database associated with your application. These defaults are stored in your application sandbox’s Library folder, in a property list file named with your application identifier.

Treat user defaults as a mutable dictionary. Set and retrieve objects using keys, just as you would with that dictionary. Defaults entries are limited to standard property list types—that is, NSString, NSNumber, NSDate, NSData, NSArray, and NSDictionary. When you need to store information that does not fall into one of these classes, consider using another file (such as one that resides in your sandbox’s Library folder) or serialize your object into NSData and store that data in defaults.

The synchronize method forces the defaults database to update to the latest changes made in memory. Synchronizing assures you that the file-based defaults data is up to date, an important factor if your application gets interrupted for some reason. The following snippet demonstrates setting, synchronizing, and retrieving data from the user defaults system:

[[NSUserDefaults standardUserDefaults]

    setObject:colors forKey:@"colors"];

[[NSUserDefaults standardUserDefaults]

    setObject:locs forKey:@"locs"];



[[NSUserDefaults standardUserDefaults] synchronize];



NSLog(@"%@", [[NSUserDefaults] objectForKey@"lastViewTag"]);

The Settings App

iPhone applications can add custom preferences into the main Settings app (see Figure 16-9). These preferences access the same application-specific user defaults that you work with programmatically. Any changes your users make to these screens update and synchronize with standard user defaults. The difference is that Settings provides a “friendly” GUI for your users and that the chances of your users stumbling across these settings is, practically zero.

A word of caution: Avoid using Settings bundles with your apps. Build your preferences directly into your app or prepare for an onslaught of customer service requests because the discoverability of this feature is marginal. I include coverage of this topic out of a sense of courtesy. Although they are not easily discoverable for users, they are particularly helpful for kiosk-style apps. When working with apps intended for trade shows or other public use, using Settings bundles helps hide those defaults items you don’t want to expose in-app.

Custom settings are listed after system settings, but otherwise look and act like the ones that Apple preloaded into your system. As the screenshots in Figure 16-9 show, custom preferences provide a variety of data interaction styles, including text fields, switches, and sliders.

Figure 16-9

Figure 16-9. (Left) Custom settings bundles for third-party applications appear on the Settings screen after the built-in settings. On the iPhone, you may have to scroll down a bit to find them. (Right) Developer-defined preferences elements can include text fields (both regular and secure), switches, sliders, multivalue choices, group titles, and child panes.

Because these settings create standard NSUserDefaults entries, you can easily query and modify any of these settings from code. For example, Recipe 16-7 defines a field called “Name” (see Figure 16-9, right screenshot, first item in the top Group). This text field stores its value to the @"name_preference" key. You can see whether the user has entered a value for this key from your application.

NSLog(@"% objectForKey:@"name_preference"];

Avoid Sensitive Information

Use settings to store nonsensitive account preferences such as usernames and option toggles. Although passwords are visually obscured with dots, they’re stored in clear text in your application sandbox. When working with sensitive information, always use your iPhone’s secure keychain instead. Settings bundles do not offer keychain integration at this time. (Keychain recipes appear in Chapter 15.)

Settings Schema

A copy of the settings schema resides in your Developer folder at /Developer/Platforms/ iPhoneOS.platform/Developer/Library/Xcode/Plug-ins/iPhoneSettingsPlistStructDefs.xcodeplugin. Xcode uses this file to check its property list syntax. In the file, you can see all the definitions and the required and optional attributes used to specify custom preferences. If Apple should ever expand or change its definitions, you’ll be able to find those changes in this file.

Defining a Settings Bundle

Each settings pane corresponds to one property list file. Recipe 16-7 shows the source for the pane in Figure 16-9 (right). It demonstrates each SDK settings type and provides a sample definition. Types include text fields (strings), sliders (floating-point numbers), switches (Boolean values), and multiple selection (one-of-n choices). In addition, you can group items and link to child panes.

To add new settings, build a dictionary and add it to the PreferencesSpecifiers array. Each individual preference dictionary needs, at a minimum, a type and a title. Some settings, like the PSGroupSpecifier group item, require nothing more to work. Others, such as text fields, use quite a few properties. You want to specify capitalization and autocorrection behaviors as well as the keyboard type and whether the password security feature obscures text, as you can see in this recipe.

To add a settings bundle to your program, follow these steps. Alternatively, you can create a new settings bundle by choosing File > New File > iPhone OS > Resource > Settings Bundle:

  1. Create each of the property lists, one for each screen. The primary plist must be named Root.plist.
  2. Create a new folder in the Finder and add your property lists to that folder.
  3. Rename the folder to Settings.bundle. OS X warns you about the name; go ahead and confirm the rename. The folder transforms into a bundle. (To view the contents of your new bundle, right-click [Control-click] and choose Show Package Contents from the contextual pop up.)
  4. Drag the bundle into the File Navigator of your Xcode project.
  5. Optionally, create a 29x29 version of your main application icon file (typically icon.png) and add it to your project with the name Icon-Settings.png. This art is used by the Settings application to label your bundle along with the application name.

When you next run your program, the settings bundle installs and makes itself available to the Settings application. Should your source have any syntax errors, you find a blank screen rather than the settings you expect. It helps to build your settings in stages to avoid this.

Recipe 16-7. Creating a Custom Settings Pane

<?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>Title</key>

    <string>YOUR_PROJECT_NAME</string>

    <key>StringsTable</key>

    <string>Root</string>

    <key>PreferenceSpecifiers</key>

    <array>

        <dict>

            <key>Type</key>

            <string>PSGroupSpecifier</string>

            <key>Title</key>

            <string>Group</string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSTextFieldSpecifier</string>

            <key>Title</key>

            <string>Name</string>

            <key>Key</key>

            <string>name_preference</string>

            <key>DefaultValue</key>

            <string></string>

            <key>IsSecure</key>

            <false/>

            <key>KeyboardType</key>

            <string>Alphabet</string>

            <key>AutocapitalizationType</key>

            <string>None</string>

            <key>AutocorrectionType</key>

            <string>No</string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSTextFieldSpecifier</string>

            <key>Title</key>

            <string>Password</string>

            <key>Key</key>

            <string>prefs_preference</string>

            <key>DefaultValue</key>

            <string></string>

            <key>IsSecure</key>

            <true/>

            <key>KeyboardType</key>

            <string>Alphabet</string>

            <key>AutocapitalizationType</key>

            <string>None</string>

            <key>AutocorrectionType</key>

            <string>No</string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSToggleSwitchSpecifier</string>

            <key>Title</key>

            <string>Enabled</string>

            <key>Key</key>

            <string>enabled_preference</string>

            <key>DefaultValue</key>

            <true/>

            <key>TrueValue</key>

            <string>YES</string>

            <key>FalseValue</key>

            <string>NO</string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSSliderSpecifier</string>

            <key>Key</key>

            <string>slider_preference</string>

            <key>DefaultValue</key>

            <real>0.5</real>

            <key>MinimumValue</key>

            <integer>0</integer>

            <key>MaximumValue</key>

            <integer>1</integer>

            <key>MinimumValueImage</key>

            <string></string>

            <key>MaximumValueImage</key>

            <string></string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSMultiValueSpecifier</string>

            <key>Key</key>

            <string>multi_preference</string>

            <key>DefaultValue</key>

            <string>One</string>

            <key>Title</key>

            <string>MultiValue</string>

            <key>Titles</key>

            <array>

                <string>one</string>

                <string>two</string>

                <string>three</string>

                <string>four</string>

            </array>

            <key>Values</key>

            <array>

                <string>one</string>

                <string>two</string>

                <string>three</string>

                <string>four</string>

            </array>

        </dict>



        <dict>

            <key>Type</key>

            <string>PSGroupSpecifier</string>

            <key>Title</key>

            <string>Info</string>

        </dict>

        <dict>

            <key>Type</key>

            <string>PSChildPaneSpecifier</string>

            <key>Title</key>

            <string>Legal</string>

            <key>File</key>

            <string>Legal</string>

        </dict>

    </array>

</dict>

</plist>

Settings and Users

Although settings bundles offer a well-defined resource for developers to centralize their user-defined defaults, real-world experience suggests they’re a feature you won’t want to use. Few iOS users are aware of third-party settings outside their applications. Even fewer actually use those settings on a regular basis. Most users want to stay within the bounds of an application for all app-related tasks, including settings.

Because of this, many (if not most) App Store developers have moved away from settings bundles and brought their settings directly into the application. Adding settings views allows users to find and set preferences easily. Unfortunately, creating those screens is labor intensive and fussy.

There is, fortunately, a middle ground between relying solely on settings bundles and building your own views. The Llama Settings project at Google Code (http://code.google.com/p/llamasettings/) offers a set of classes that read property lists (including from your settings bundles), allowing you to display settings screens within your application without much extra work or overhead. The project was developed and is maintained by Scott Lawrence.

Open sourced, the Llama Settings classes provide similar kinds of display and interactive elements, including group titles, sliders, and switches. In addition, the project adds support for color selectors, URL launchers, and more. Although these items are not supported in Apple’s Settings app, you can use them within your program by defining standard property lists without further programming.

Checking User Defaults

You may solicit and set defaults via settings bundles, application-based views, code-level access, or a hybrid of these approaches. When using those settings, be aware that certain items may not yet exist. If a user hasn’t opened your settings bundle, the default settings you specified in the bundle’s property lists may not have ever been set. For most objects, you can test for this via objectForKey:. This method returns nil for nonexistent keys.

Here’s one reason a nil value may play a role in your programming: One default that you’ll always want to set through code is a “last version” key. This key records the application version that was most recently run. You’ll want to check for this default whenever your application launches.

If that default is nil, the application is a new install. You may want to prepare files and perform other setup tasks at first run. After that setup, set a value for the key, one that indicates the currently deployed app version. (And don’t forget to synchronize after setting that key.)

It doesn’t end with a check for nil, though. You’ll always know when the user has just upgraded from a previous version by checking that setting. When the last run version differs from your current version, you have the opportunity to perform any updates that bring your user into data compliance for the most recent release.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020