Overview
Hello Friends, in this tutorial we are going to learn about how we can implement Setting Bundle in our project and how we can use it.
iOS, Foundation framework provides the low level mechanism to store preference data. Using Setting Bundle you can configure application level settings. Setting Bundle’s Data is managed by the UserDefault.
Before creating the project let’s discuss the Preference Item and its properties.
1) Group: The group type is for organizing groups of preferences on a single page. The group type does not represent a configurable preference. It simply contains a title string that is displayed immediately before one or more configurable preferences.
Properties:
a) Type: This property specifies the type of the preference. E.g TextField, Title, Toggle Switch, Slider etc
b) Title: This property is used to set the title of the preference.
These two properties are common for all the preference item.
2) Title: The title type displays a read-only string value. You can use this type to display read-only preference values.
Properties:
a) Default Value: This property is used to set the default value. E.g Build Version
b) Identifier: This unique identifier is used to save and retrieve the preference value.
3) TextField: The text field type displays a title (optional) and an editable text field. It is used to take a input from the User.
The key for this type is PSTextFieldSpecifier.
Properties:
a) Identifier: This unique identifier is used to save and retrive the preference value.
b) TextField Is Secure: This property is used to enter the secure text e.g Password. It has two values: 1. Yes, 2. No
c) KeyboardType: This property is used to set the keyboard type e.g URL, Email Address, Number Pad etc.
d) Auto Capitalization: This property is used to set the capitalization. E.g Sentence, Word, All Character
4) Toggle Switch: The toggle switch is an ON/OFF type button. One can use this to configure a preference where one of two values is required.
Properties:
a) Default Value: Used to set the default toggle as an ON or OFF. It has two values “YES” and “NO”
b) Value for OFF: Used to set the toggle OFF value
c) Value for ON: Used to set the toggle ON value
5) Multi Value: The multi value type lets the user select one value from a list of values. You can use this type for a preference that supports a set of contradictory values. The values can be of any type.
Properties:
a) Titles: This property is used to set the title of the Multi items.
b) Values: This property is used to set the value for the title.
6) Slider: The slider type displays a slider control. You can use this type for a preference that represents a range of values. The value for this type is a real number whose minimum and maximum value you specify.
Properties:
a) Minimum Value: Used to set the Minimum value of the Slider.
b) Maximum Value: Used to set the Maximum value of the Slider.
How to Implement:
1) Configure new project in XCode
2) Press cmd + N
3) Select the setting bundle from the Resource
Now we are ready to start the implementation. We are going to take an Input from the user, Reset the app data and display the Build version and Number.
Make a class which handles the Setting Bundle Data. In the below code, I have implemented the functionality to Reset the Application data and Sets the Build Version and Number.
import Foundation class SettingsBundleHelper { struct SettingsBundleKeys { static let Reset = "reset_preference" static let BuildVersionKey = "build_preference" static let AppVersionKey = "version_preference" } class func checkAndExecuteSettings() { if UserDefaults.standard.bool(forKey: SettingsBundleKeys.Reset) { // UserDefaults.standard.set(false, forKey: SettingsBundleKeys.Reset) let appDomain: String? = Bundle.main.bundleIdentifier UserDefaults.standard.removePersistentDomain(forName: appDomain!) //reset userDefaults.. //CoreDataDataModel().deleteAllData() //delete all other user data here.. UserDefaults.standard.synchronize() print(Array(UserDefaults.standard.dictionaryRepresentation().keys).count) } } class func setVersionAndBuildNumber() { let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String UserDefaults.standard.set(version, forKey: "version_preference") let build: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String UserDefaults.standard.set(build, forKey: "build_preference") } }
I have Called this Function from the AppDelegate.
func applicationDidBecomeActive(_ application: UIApplication) {\ SettingsBundleHelper.checkAndExecuteSettings() SettingsBundleHelper.setVersionAndBuildNumber() }
When app becomes Active it will check all time Setting Preference.
How to fetch the data from the Setting Bundle?
To Fetch the User Default data we have to add the Observer and register the UserDefault in our code which notifies that something has been changed in the User Default.
/*! -registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them. Default values from Defaults Configuration Files will automatically be registered. */ open func register(defaults registrationDictionary: [String : Any]) /*! NSUserDefaultsDidChangeNotification is posted whenever any user defaults changed within the current process, but is not posted when ubiquitous defaults change, or when an outside process changes defaults. Using key-value observing to register observers for the specific keys of interest will inform you of all updates, regardless of where they're from. */ public class let didChangeNotification: NSNotification.Name
Call addNotificationObserver() and registerSettingsBundle() in ViewDidLoad.
func registerSettingsBundle() { let appDefaults = [String:AnyObject]() UserDefaults.standard.register(defaults: appDefaults) }
func addNotificationObserver() { NotificationCenter.default.addObserver(self, selector: #selector(fetchDefaultSettingValues), name: UserDefaults.didChangeNotification, object: nil) }
@objc func fetchDefaultSettingValues() { sbObjData.name = sbObjData.getUserDefaultStringValue(key: "name_preference") sbObjData.password = sbObjData.getUserDefaultStringValue(key: "password_preference") sbObjData.reset = sbObjData.getUserDefaultBoolValue(key: "reset_preference") let experiance_status = sbObjData.getUserDefaultStringValue(key: "experience_preference") if experiance_status == ExperianceLevel.Beginner.rawValue{ sbObjData.expertyLevel = .Beginner }else if experiance_status == ExperianceLevel.Expert.rawValue{ sbObjData.expertyLevel = .Expert }else if experiance_status == ExperianceLevel.Master.rawValue{ sbObjData.expertyLevel = .Master } self.tableView.reloadData() }
enum ExperianceLevel: String { case Beginner = "Beginner" case Expert = "Expert" case Master = "Master" } class SettingBundleData: NSObject { var name: String? var password: String? var reset:Bool = false var expertyLevel: ExperianceLevel = .Beginner override init() { } func getUserDefaultStringValue(key: String)-> String { return UserDefaults.standard.string(forKey: key) ?? "" } func getUserDefaultBoolValue(key: String)-> Bool { return UserDefaults.standard.bool(forKey: key) } }