iPhone settings.bundle issues – Loading Defaults

 

Here's something i hadn't realised but it's the reason why shrinkURL 1.1 was rejected by Apple recently.

ShrinkURL 1.1 uses application settings to store the default shortening service to be used, along with the bitly username and API Key. When an application is installed that has application settings the settings.bundle isn't actually created, at least not until you enter the settings page for that particular application from within the iPhone itself, therefore code has to be introduced to load the default settings from the root.plist.

The root.plist settings bundle

The Settings Bundle

In the example below, the code is checking for the 'service' to see it it exists in root.plist, if it doesn't (meaning the settings.bundle hasn't been created) it will load the defaults for each key from the settings.bundle into the program. This is performed at the start of viewDidLoad.

// check application settings bundle is there
NSString *serviceCheck = [[NSUserDefaults standardUserDefaults] stringForKey:"service"];

if(!serviceCheck) {
// If the default value doesn't exist then we need to manually set them.
[self registerDefaultsFromSettingsBundle];
serviceCheck = [[NSUserDefaults standardUserDefaults] stringForKey:"service"];
}

The method to call if the settings.bundle doesn't exist, this loads the defaults into the program.

- (void)registerDefaultsFromSettingsBundle {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:"Settings" ofType:"bundle"]; 

if(!settingsBundle) {
NSLog("Could not find Settings.bundle");
return;
} 

NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile: [settingsBundle stringByAppendingPathComponent:@"Root.plist"]];
NSArray *preferences = [settings objectForKey:@"PreferenceSpecifiers"];

NSMutableDictionary *defaultsToRegister = [[NSMutableDictionary alloc] initWithCapacity:[preferences count]];

for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:@"Key"]; 

if(key) {
[defaultsToRegister setObject:[prefSpecification objectForKey:@"DefaultValue"] forKey:key];
}
} 

[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}

Thanks must go to Paul Solt's website for the useful piece of code.

Similar Posts: