iPhone App : How to get default value from root.plist? - iphone

I am working on an iPhone app
I read a key from root.plist like this :
NSString *Key1Var = [[NSUserDefaults standardUserDefaults] stringForKey:#"Key1"];
("Key1" is a PSMultiValueSpecifier for which a default string value has been set already in root.plist)
That works fine, once the user makes settings.
But if the user runs the app before he does any setting, he will get nil for "Key1".
In such case, I was expecting the default value that i had set for "Key1".
what i need to do,
so that the user does not have to do setting, to make application run for the first time?
Regards,
Harish

See this question for a complete solution.
You essentially want to run this code before accessing the setting:
- (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];
}
This will load the default values into the standardUserDefaults object so you will no longer get back nil values, and you don't have to duplicate the default settings in your code.

I do this early after launch, before I try to get my settings:
userDefaultsValuesPath=[[NSBundle mainBundle] pathForResource:#"UserDefaults"
ofType:#"plist"];
userDefaultsValuesDict=[NSDictionary dictionaryWithContentsOfFile:userDefaultsValuesPath];
// set them in the standard user defaults
[[NSUserDefaults standardUserDefaults] registerDefaults:userDefaultsValuesDict];
if (![[NSUserDefaults standardUserDefaults] synchronize])
NSLog(#"not successful in writing the default prefs");

A Swift 3 version based on Mike Weller's original solution if anyone needs it:
static func registerDefaultsFromSettingsBundle() {
guard let settingsBundle = Bundle.main.url(forResource: "Settings", withExtension: "bundle") else {
print("Could not find Settings.bundle")
return
}
guard let settings = NSDictionary(contentsOf: settingsBundle.appendingPathComponent("Root.plist")) else {
print("Couldn't find Root.plist in settings bundle")
return
}
guard let preferences = settings.object(forKey: "PreferenceSpecifiers") as? [[String: AnyObject]] else {
print("Root.plist has an invalid format")
return
}
var defaultsToRegister = [String: AnyObject]()
for var p in preferences {
if let k = p["Key"] as? String, let v = p["DefaultValue"] {
print("Registering " + v.debugDescription + " for key " + k)
defaultsToRegister[k] = v as AnyObject
}
}
UserDefaults.standard.register(defaults: defaultsToRegister)
}

Here is the code I use in iOS 7, based heavily on Mike Weller's code above.
Put this method in your AppDelegate.m:
- (void)registerDefaultsFromSettingsBundleWithPlist:(NSString *)plist {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
if(!settingsBundle) {
NSLog(#"Could not find Settings.bundle");
return;
}
NSString *bundle = [NSString stringWithFormat:#"%#.plist",plist];
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:bundle]];
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];
}
And then call it for every settings file you're using (for nested settings), from some place early in your code like didFinishLaunchingWithOptions:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
//register default settings into NSUserDefaults
#try {
[self registerDefaultsFromSettingsBundleWithPlist:#"Root"];
[self registerDefaultsFromSettingsBundleWithPlist:#"Chat"];
[self registerDefaultsFromSettingsBundleWithPlist:#"IVR"];
[self registerDefaultsFromSettingsBundleWithPlist:#"Video"];
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
NSLog(#"Try adding the Default Value field to each preference item in the Settings.bundle plist files.");
}
#finally {
}
...

I've translated Mike Weller's solution into Swift 2.0/iOS 9 and made it work for my App:
func registerDefaultsFromSettingsBundle() {
guard let settingsBundle = NSBundle.mainBundle().URLForResource("Settings", withExtension:"bundle") else {
NSLog("Could not find Settings.bundle")
return;
}
guard let settings = NSDictionary(contentsOfURL: settingsBundle.URLByAppendingPathComponent("Root.plist")) else {
NSLog("Could not find Root.plist in settings bundle")
return
}
guard let preferences = settings.objectForKey("PreferenceSpecifiers") as? [[String: AnyObject]] else {
NSLog("Root.plist has invalid format")
return
}
var defaultsToRegister = [String: AnyObject]()
for var p in preferences {
if let k = p["Key"] as? String, v = p["DefaultValue"] {
NSLog("%#", "registering \(v) for key \(k)")
defaultsToRegister[k] = v
}
}
NSUserDefaults.standardUserDefaults().registerDefaults(defaultsToRegister)
}

In my application delegate, I override the +initialize method and register new application default preferences.
For example:
+ (void) initialize {
if ([self class] == [MyAppDelegate class]) {
// initialize user defaults dictionary
BOOL isFirstTimeRun = YES;
BOOL isKeychainTurnedOn = NO;
BOOL isSSLTurnedOn = YES;
NSString *testURLString = #"http://stackoverflow.com";
NSMutableDictionary *resourceDict = [NSMutableDictionary dictionary];
[resourceDict setObject:[NSNumber numberWithBool:isFirstTimeRun] forKey:kIsFirstTimeRunKey];
[resourceDict setObject:[NSNumber numberWithBool:isKeychainTurnedOn] forKey:kIsKeychainTurnedOnKey];
[resourceDict setObject:[NSNumber numberWithBool:isSSLTurnedOn] forKey:kIsSSLTurnedOnKey];
[resourceDict setObject:testURLString forKey:kTestURLString];
[[NSUserDefaults standardUserDefaults] registerDefaults:resourceDict];
}
}

NSBundle* mainBundle = [NSBundle mainBundle]; 
 
// Reads the value of the custom key I added to the Info.plist
NSString *value = [mainBundle objectForInfoDictionaryKey:#"key"];
//Log the value
NSLog(#"Value = %#", value);
// Get the value for the "Bundle version" from the Info.plist
[mainBundle objectForInfoDictionaryKey:#"CFBundleVersion"];
// Get the bundle identifier
[mainBundle bundleIdentifier];

Related

Javascript Youtube API: buffering for ever - UIWebView iOS

I am using the YouTube API in UIWebView.
I have created a NSString with the HTML5 player that I load in the UIWebView. Everything works perfectly on iPhone 5 and iPad.
But, if I test the app using an iPhone 4, the player returns the buffering state all the time. Only if I explicitly press the play button, the player starts playing, without stopping again for buffering. It seems that although the video has been buffered, the player still gives me this state.
Is anyone aware of this problem? Any idea?
Thank you very much in advance!!
In LBYouTubePlayerViewController.m file
Replace Following method on yr old Method....
then test...
-(NSURL*)_extractYouTubeURLFromFile:(NSString *)html error:(NSError *__autoreleasing *)error {
NSString *JSONStart = nil;
// NSString *JSONStartFull = #"ls.setItem('PIGGYBACK_DATA', \")]}'";
NSString *JSONStartFull = #"bootstrap_data = \")]}'";
NSString *JSONStartShrunk = [JSONStartFull stringByReplacingOccurrencesOfString:#" " withString:#""];
if ([html rangeOfString:JSONStartFull].location != NSNotFound)
JSONStart = JSONStartFull;
else if ([html rangeOfString:JSONStartShrunk].location != NSNotFound)
JSONStart = JSONStartShrunk;
if (JSONStart != nil) {
NSScanner* scanner = [NSScanner scannerWithString:html];
[scanner scanUpToString:JSONStart intoString:nil];
[scanner scanString:JSONStart intoString:nil];
NSString *JSON = nil;
[scanner scanUpToString:#"}\";" intoString:&JSON];
JSON = [NSString stringWithFormat:#"%#}",JSON]; // Add closing bracket } to get vallid JSON again
// [scanner scanUpToString:#"\");" intoString:&JSON];
JSON = [self _unescapeString:JSON];
NSError* decodingError = nil;
NSDictionary* JSONCode = nil;
// First try to invoke NSJSONSerialization (Thanks Mattt Thompson)
id NSJSONSerializationClass = NSClassFromString(#"NSJSONSerialization");
SEL NSJSONSerializationSelector = NSSelectorFromString(#"dataWithJSONObject:options:error:");
if (NSJSONSerializationClass && [NSJSONSerializationClass respondsToSelector:NSJSONSerializationSelector]) {
JSONCode = [NSJSONSerialization JSONObjectWithData:[JSON dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:&decodingError];
}
else {
JSONCode = [JSON objectFromJSONStringWithParseOptions:JKParseOptionNone error:&decodingError];
}
if (decodingError) {
// Failed
*error = decodingError;
}
else {
// Success
NSDictionary *dict = [JSONCode objectForKey:#"content"];
NSDictionary *dictTemp = [dict objectForKey:#"video"];
NSArray* videos = [dictTemp objectForKey:#"fmt_stream_map"];
NSString* streamURL = nil;
if (videos.count) {
NSString* streamURLKey = #"url";
if (self.quality == LBYouTubePlayerQualityLarge) {
streamURL = [[videos objectAtIndex:0] objectForKey:streamURLKey];
}
else if (self.quality == LBYouTubePlayerQualityMedium) {
unsigned int index = MAX(0, videos.count-2);
streamURL = [[videos objectAtIndex:index] objectForKey:streamURLKey];
}
else {
streamURL = [[videos lastObject] objectForKey:streamURLKey];
}
}
if (streamURL) {
return [NSURL URLWithString:streamURL];
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:2 userInfo:[NSDictionary dictionaryWithObject:#"Couldn't find the stream URL." forKey:NSLocalizedDescriptionKey]];
}
}
}
else {
*error = [NSError errorWithDomain:kLBYouTubePlayerControllerErrorDomain code:3 userInfo:[NSDictionary dictionaryWithObject:#"The JSON data could not be found." forKey:NSLocalizedDescriptionKey]];
}
return nil;
}

Creating Files And Saving Objects In Them

Why when you call this method (saveObject: (id)object forKey: (NSString *) key), will a file not get created???
When I call it filePath is equal to nil so the (-(void) setFilePath: (NSString *)fileName) method will get called...
-(int) saveObject: (id)object forKey: (NSString *) key {
//save object into file
if(filePath == nil) {
[self setFilePath:nil];
}
mainDict = [NSMutableDictionary dictionaryWithContentsOfFile:filePath];
if(mainDict == nil) {
mainDict = [[NSMutableDictionary alloc] init];
}
[mainDict setObject:object forKey:key];
if(![mainDict writeToFile:filePath atomically:YES]) {
if(object == nil) {
return 3;
}
if(key == nil) {
return 4;
}
return 2; //ERROR could not write object to file
} else {
if(shouldUseCache == YES) {
cacheStatus = 2; //New Caches need to be updated
}
return 1; //SUCCESS object saved to file
}
//RETURN KEY's
// *1 SUCCESS object saved to file
// *2 ERROR could not write object to file
// *3 ERROR object variable = nil
// *4 ERROR key variable = nil
}
-(void) setFilePath: (NSString *)fileName {
paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
documentsDirectory = [paths objectAtIndex:0];
if(fileName == nil) {
fileName = #"savedObjects";
}
filePath = [NSString stringWithFormat:#"%#/%#.plist",documentsDirectory, fileName];
}
I think the problem is with the contents of the dictionary you are intending to write.
You are adding object to your dictionary.
That object must only contain members of types:NSArray , NSDictionary , NSString , NSDate, NSData and NSNumber. If your object contains a int or float , or anything other than these , it won't write.
You can read more here

Parse NSURL query property

I have a URL like myApp://action/1?parameter=2&secondparameter=3
With the property query I get following part of my URL
parameter=2&secondparameter=3
Is there any way easy to put this in a NSDictionary or an Array?
Thx a lot
You can use queryItems in URLComponents.
When you get this property’s value, the NSURLComponents class parses the query string and returns an array of NSURLQueryItem objects, each of which represents a single key-value pair, in the order in which they appear in the original query string.
Swift
let url = "http://example.com?param1=value1&param2=param2"
let queryItems = URLComponents(string: url)?.queryItems
let param1 = queryItems?.filter({$0.name == "param1"}).first
print(param1?.value)
Alternatively, you can add an extension on URL to make things easier.
extension URL {
var queryParameters: QueryParameters { return QueryParameters(url: self) }
}
class QueryParameters {
let queryItems: [URLQueryItem]
init(url: URL?) {
queryItems = URLComponents(string: url?.absoluteString ?? "")?.queryItems ?? []
print(queryItems)
}
subscript(name: String) -> String? {
return queryItems.first(where: { $0.name == name })?.value
}
}
You can then access the parameter by its name.
let url = "http://example.com?param1=value1&param2=param2"
print(url.queryParameters["param1"])
I had reason to write some extensions for this behavior that might come in handy. First the header:
#import <Foundation/Foundation.h>
#interface NSString (XQueryComponents)
- (NSString *)stringByDecodingURLFormat;
- (NSString *)stringByEncodingURLFormat;
- (NSMutableDictionary *)dictionaryFromQueryComponents;
#end
#interface NSURL (XQueryComponents)
- (NSMutableDictionary *)queryComponents;
#end
#interface NSDictionary (XQueryComponents)
- (NSString *)stringFromQueryComponents;
#end
These methods extend NSString, NSURL, and NSDictionary, to allow you to convert to and from query components strings and dictionary objects containing the results.
Now the related .m code:
#import "XQueryComponents.h"
#implementation NSString (XQueryComponents)
- (NSString *)stringByDecodingURLFormat
{
NSString *result = [self stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
- (NSString *)stringByEncodingURLFormat
{
NSString *result = [self stringByReplacingOccurrencesOfString:#" " withString:#"+"];
result = [result stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
- (NSMutableDictionary *)dictionaryFromQueryComponents
{
NSMutableDictionary *queryComponents = [NSMutableDictionary dictionary];
for(NSString *keyValuePairString in [self componentsSeparatedByString:#"&"])
{
NSArray *keyValuePairArray = [keyValuePairString componentsSeparatedByString:#"="];
if ([keyValuePairArray count] < 2) continue; // Verify that there is at least one key, and at least one value. Ignore extra = signs
NSString *key = [[keyValuePairArray objectAtIndex:0] stringByDecodingURLFormat];
NSString *value = [[keyValuePairArray objectAtIndex:1] stringByDecodingURLFormat];
NSMutableArray *results = [queryComponents objectForKey:key]; // URL spec says that multiple values are allowed per key
if(!results) // First object
{
results = [NSMutableArray arrayWithCapacity:1];
[queryComponents setObject:results forKey:key];
}
[results addObject:value];
}
return queryComponents;
}
#end
#implementation NSURL (XQueryComponents)
- (NSMutableDictionary *)queryComponents
{
return [[self query] dictionaryFromQueryComponents];
}
#end
#implementation NSDictionary (XQueryComponents)
- (NSString *)stringFromQueryComponents
{
NSString *result = nil;
for(__strong NSString *key in [self allKeys])
{
key = [key stringByEncodingURLFormat];
NSArray *allValues = [self objectForKey:key];
if([allValues isKindOfClass:[NSArray class]])
for(__strong NSString *value in allValues)
{
value = [[value description] stringByEncodingURLFormat];
if(!result)
result = [NSString stringWithFormat:#"%#=%#",key,value];
else
result = [result stringByAppendingFormat:#"&%#=%#",key,value];
}
else {
NSString *value = [[allValues description] stringByEncodingURLFormat];
if(!result)
result = [NSString stringWithFormat:#"%#=%#",key,value];
else
result = [result stringByAppendingFormat:#"&%#=%#",key,value];
}
}
return result;
}
#end
Something like that:
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *param in [url componentsSeparatedByString:#"&"]) {
NSArray *elts = [param componentsSeparatedByString:#"="];
if([elts count] < 2) continue;
[params setObject:[elts lastObject] forKey:[elts firstObject]];
}
Note : This is sample code. All error cases are not managed.
Try this ;)!
NSString *query = #"parameter=2&secondparameter=3"; // replace this with [url query];
NSArray *components = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
for (NSString *component in components) {
NSArray *subcomponents = [component componentsSeparatedByString:#"="];
[parameters setObject:[[subcomponents objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]
forKey:[[subcomponents objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
All previous posts do not do the url encoding properly. I would suggest the following methods:
+(NSString*)concatenateQuery:(NSDictionary*)parameters {
if([parameters count]==0) return nil;
NSMutableString* query = [NSMutableString string];
for(NSString* parameter in [parameters allKeys])
[query appendFormat:#"&%#=%#",[parameter stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet],[[parameters objectForKey:parameter] stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet]];
return [[query substringFromIndex:1] copy];
}
+(NSDictionary*)splitQuery:(NSString*)query {
if([query length]==0) return nil;
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
for(NSString* parameter in [query componentsSeparatedByString:#"&"]) {
NSRange range = [parameter rangeOfString:#"="];
if(range.location!=NSNotFound)
[parameters setObject:[[parameter substringFromIndex:range.location+range.length] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] forKey:[[parameter substringToIndex:range.location] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
else [parameters setObject:[[NSString alloc] init] forKey:[parameter stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
}
return [parameters copy];
}
According to the already very clean answer of Onato I wrote an extension for NSURL in Swift where you can get a query param like this:
e.g. the URL contains the pair param=some_value
let queryItem = url.queryItemForKey("param")
let value = queryItem.value // would get String "someValue"
The extension looks like:
extension NSURL {
var allQueryItems: [NSURLQueryItem] {
get {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
let allQueryItems = components.queryItems!
return allQueryItems as [NSURLQueryItem]
}
}
func queryItemForKey(key: String) -> NSURLQueryItem? {
let predicate = NSPredicate(format: "name=%#", key)!
return (allQueryItems as NSArray).filteredArrayUsingPredicate(predicate).first as? NSURLQueryItem
}
}
Here is the extension in swift:
extension NSURL{
func queryParams() -> [String:AnyObject] {
var info : [String:AnyObject] = [String:AnyObject]()
if let queryString = self.query{
for parameter in queryString.componentsSeparatedByString("&"){
let parts = parameter.componentsSeparatedByString("=")
if parts.count > 1{
let key = (parts[0] as String).stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let value = (parts[1] as String).stringByReplacingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
if key != nil && value != nil{
info[key!] = value
}
}
}
}
return info
}
}
The preferred way to deal with URLs is now NSURLComponents. In particular the queryItems property which returns an NSArray of params.
If you want the params in a NSDictionary, here's a method:
+(NSDictionary<NSString *, NSString *>*)queryParamsFromURL:(NSURL*)url
{
NSURLComponents* urlComponents = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO];
NSMutableDictionary<NSString *, NSString *>* queryParams = [NSMutableDictionary<NSString *, NSString *> new];
for (NSURLQueryItem* queryItem in [urlComponents queryItems])
{
if (queryItem.value == nil)
{
continue;
}
[queryParams setObject:queryItem.value forKey:queryItem.name];
}
return queryParams;
}
Caveat: URLs can have repeated params, but the dictionary will only contain the last value of any duplicated param. If that is undesirable, use the queryItems array directly.
For those using Bolts Framework you can use:
NSDictionary *parameters = [BFURL URLWithURL:yourURL].inputQueryParameters;
Remember to import:
#import <Bolts/BFURL.h>
If you happen to have Facebook SDK in your project, you also have Bolts. Facebook is using this framework as a dependency.
Swift 2.1
Oneliner:
"p1=v1&p2=v2".componentsSeparatedByString("&").map {
$0.componentsSeparatedByString("=")
}.reduce([:]) {
(var dict: [String:String], p) in
dict[p[0]] = p[1]
return dict
}
// ["p1": "v1", "p2": "v2"]
Used as an extension on NSURL:
extension NSURL {
/**
* URL query string as dictionary. Empty dictionary if query string is nil.
*/
public var queryValues : [String:String] {
get {
if let q = self.query {
return q.componentsSeparatedByString("&").map {
$0.componentsSeparatedByString("=")
}.reduce([:]) {
(var dict: [String:String], p) in
dict[p[0]] = p[1]
return dict
}
} else {
return [:]
}
}
}
}
Example:
let url = NSURL(string: "http://example.com?p1=v1&p2=v2")!
let queryDict = url.queryValues
// ["p1": "v1", "p2": "v2"]
Please note, if using OS X 10.10 or iOS 8 (or later), it's probably better to use NSURLComponents and the queryItems property and create the dictionary from the NSURLQueryItems directly.
Here's a NSURLComponents based NSURL extension solution:
extension NSURL {
/// URL query string as a dictionary. Empty dictionary if query string is nil.
public var queryValues : [String:String] {
get {
guard let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false) else {
return [:]
}
guard let queryItems = components.queryItems else {
return [:]
}
var result:[String:String] = [:]
for q in queryItems {
result[q.name] = q.value
}
return result
}
}
}
A footnote to the NSURL extension is that it's actually possible in Swift to give the property the same name as the existing string property—query. I didn't know until I tried it, but the polymorphism in Swift lets you differ only on the return type. So if the extended NSURL property is public var query: [String:String] it works. I didn't use this in the example as I find it a little bit crazy, but it does work ...
I published a simple class doing the job under MIT:
https://github.com/anegmawad/URLQueryToCocoa
With it you can have arrays and objects in the query, which are collected and glued together
For Example
users[0][firstName]=Amin&users[0][lastName]=Negm&name=Devs&users[1][lastName]=Kienle&users[1][firstName]=Christian
will become:
#{
name : #"Devs",
users :
#[
#{
firstName = #"Amin",
lastName = #"Negm"
},
#{
firstName = #"Christian",
lastName = #"Kienle"
}
]
}
You can think of it as a URL query counterpart of NSJSONSerializer.
It looks that you are using it to process incoming data from another iOS application. If so, this is what I use for the same purpose.
Initial call (e.g. in external application):
UIApplication *application = [UIApplication sharedApplication];
NSURL *url = [NSURL URLWithString:#"myApp://action/1?parameter=2&secondparameter=3"];
if ([application canOpenURL:url]) {
[application openURL:url];
NSLog(#"myApp is installed");
} else {
NSLog(#"myApp is not installed");
}
Method to extract QueryString data from NSURL and save as NSDictionary:
-(NSDictionary *) getNSDictionaryFromQueryString:(NSURL *)url {
NSMutableDictionary *result = [[NSMutableDictionary alloc] init];
NSRange needle = [url.absoluteString rangeOfString:#"?" options:NSCaseInsensitiveSearch];
NSString *data = nil;
if(needle.location != NSNotFound) {
NSUInteger start = needle.location + 1;
NSUInteger end = [url.absoluteString length] - start;
data = [url.absoluteString substringWithRange:NSMakeRange(start, end)];
}
for (NSString *param in [data componentsSeparatedByString:#"&"]) {
NSArray *keyvalue = [param componentsSeparatedByString:#"="];
if([keyvalue count] == 2){
[result setObject:[keyvalue objectAtIndex:1] forKey:[keyvalue objectAtIndex:0]];
}
}
return result;
}
Usage:
NSDictionary *result = [self getNSDictionaryFromQueryString:url];
This class is a nice solution for url parsing.
.h file
#interface URLParser : NSObject {
NSArray *variables;
}
#property (nonatomic, retain) NSArray *variables;
- (id)initWithURLString:(NSString *)url;
- (NSString *)valueForVariable:(NSString *)varName;
#end
.m file
#import "URLParser.h"
#implementation URLParser
#synthesize variables;
- (id) initWithURLString:(NSString *)url{
self = [super init];
if (self != nil) {
NSString *string = url;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:#"&?"]];
NSString *tempString;
NSMutableArray *vars = [NSMutableArray new];
[scanner scanUpToString:#"?" intoString:nil]; //ignore the beginning of the string and skip to the vars
while ([scanner scanUpToString:#"&" intoString:&tempString]) {
[vars addObject:[tempString copy]];
}
self.variables = vars;
}
return self;
}
- (NSString *)valueForVariable:(NSString *)varName {
for (NSString *var in self.variables) {
if ([var length] > [varName length]+1 && [[var substringWithRange:NSMakeRange(0, [varName length]+1)] isEqualToString:[varName stringByAppendingString:#"="]]) {
NSString *varValue = [var substringFromIndex:[varName length]+1];
return varValue;
}
}
return nil;
}
#end
Hendrik wrote a nice example for extension in this question, however I had to re-write it to not use any objective-c library methods. Using NSArray in swift is not the correct approach.
This is the result, all swift and a bit more safe. The usage example will be less lines of code with Swift 1.2.
public extension NSURL {
/*
Set an array with all the query items
*/
var allQueryItems: [NSURLQueryItem] {
get {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
if let allQueryItems = components.queryItems {
return allQueryItems as [NSURLQueryItem]
} else {
return []
}
}
}
/**
Get a query item form the URL query
:param: key The parameter to fetch from the URL query
:returns: `NSURLQueryItem` the query item
*/
public func queryItemForKey(key: String) -> NSURLQueryItem? {
let filteredArray = filter(allQueryItems) { $0.name == key }
if filteredArray.count > 0 {
return filteredArray.first
} else {
return nil
}
}
}
Usage:
let queryItem = url.queryItemForKey("myItem")
Or, more detailed usage:
if let url = NSURL(string: "http://www.domain.com/?myItem=something") {
if let queryItem = url.queryItemForKey("myItem") {
if let value = queryItem.value {
println("The value of 'myItem' is: \(value)")
}
}
}
try this:
-(NSDictionary *)getUrlParameters:(NSString *)url{
NSArray *justParamsArr = [url componentsSeparatedByString:#"?"];
url = [justParamsArr lastObject];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *param in [url componentsSeparatedByString:#"&"]) {
NSArray *elts = [param componentsSeparatedByString:#"="];
if([elts count] < 2) continue;
[params setObject:[elts lastObject] forKey:[elts firstObject]];
}
return params;
}
Fairly compact approach:
func stringParamsToDict(query: String) -> [String: String] {
let params = query.components(separatedBy: "&").map {
$0.components(separatedBy: "=")
}.reduce(into: [String: String]()) { dict, pair in
if pair.count == 2 {
dict[pair[0]] = pair[1]
}
}
return params
}
Most robust solution if you are using a URL to pass data from the web app to the phone and you want to pass arrays, numbers, strings, ...
JSON encode your object in PHP
header("Location: myAppAction://".urlencode(json_encode($YOUROBJECT)));
And JSON decode the result in iOS
NSData *data = [[[request URL] host] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *packed = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

read a Dictionary type PSMultiValueSpecifier from NSUserDefault into a UITableView

Does anyone know how to easily read a Dictionary type PSMultiValueSpecifier from NSUserDefault into a UITableView control and save changes back to NSUserDefaults using iPhone SDK 3.0? If so, can you post some specific code to efficiently do this?
First to better access the specifier values inside the bundle I used the following code to turn them into a dictionary.
NSString* settingsBundle = [[[NSBundle mainBundle]
pathForResource:#"Settings"
ofType:#"bundle"]
stringByAppendingPathComponent:#"Root.plist"];
NSDictionary* rootPlist = [NSDictionary dictionaryWithContentsOfFile:settingsBundle];
if (rootPlist == nil)
return nil;
NSArray* specifiers = [rootPlist objectForKey:#"PreferenceSpecifiers"];
NSDictionary *multiValueSpecifier = nil;
for (NSDictionary *specifier in specifiers)
{
if ([[specifier objectForKey:#"Key"] isEqualToString:speficierKey] == YES &&
[[specifier objectForKey:#"Type"] isEqualToString:#"PSMultiValueSpecifier"] == YES)
{
multiValueSpecifier = specifier;
break;
}
}
if (multiValueSpecifier == nil)
return nil;
NSArray* titlesArray = [multiValueSpecifier objectForKey:#"Titles"];
NSArray* valuesArray = [multiValueSpecifier objectForKey:#"Values"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:titlesArray
forKeys:valuesArray];
return dictionary;
Well now if from your UI you did select something you need to store the KEY and not the VALUE of the dictionary.
[[NSUserDefaults standardUserDefaults] setObject:dictionaryKey forKey:#"myMultiValueSpecifier_preference"];

Can you make the settings in Settings.bundle default even if you don't open the Settings App

I have an iPhone application with a settings.bundle that handles various settings for my application. I can set default values in my root.plist file (using the DefaultValue property), but these only get used the first time the user opens the settings app. Is there any way to get these values written out when your application installs? I know I can just write code that checks for the first launch of my app and then write them out, but then they are in two different places.
Here is an entry from my root.plist as an example:
<dict>
<key>Type</key>
<string>PSToggleSwitchSpecifier</string>
<key>Title</key>
<string>Open To Top Location</string>
<key>Key</key>
<string>open_top_location</string>
<key>DefaultValue</key>
<string>YES</string>
<key>TrueValue</key>
<string>YES</string>
<key>FalseValue</key>
<string>NO</string>
</dict>
The end result should be that if I ask for 'open_to_top_location' I get a YES, instead of it not being there at all until the first time the user opens the Settings app.
Any ideas?
If I understood you correctly, you want to avoid having default values specified twice (once as "DefaultValue" keys in your Settings.bundle/Root.plist file, and once in your app initialization code) so you do not have to keep them in sync.
Since Settings.bundle is stored within the app bundle itself, you can just read the default values given there. I put together some sample code that looks at the Settings bundle and reads the default values for every key there. Note that this does not write out the default keys; if they don't exist, you'll need to read and register them at every launch (feel free to change this). I've only done some cursory tests, so make sure it works for you in all cases.
- (void)applicationDidFinishLaunching:(UIApplication *)application {
NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:#"name"];
NSLog(#"name before is %#", name);
// Note: this will not work for boolean values as noted by bpapa below.
// If you use booleans, you should use objectForKey above and check for null
if(!name) {
[self registerDefaultsFromSettingsBundle];
name = [[NSUserDefaults standardUserDefaults] stringForKey:#"name"];
}
NSLog(#"name after is %#", name);
}
- (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 && [[prefSpecification allKeys] containsObject:#"DefaultValue"]) {
[defaultsToRegister setObject:[prefSpecification objectForKey:#"DefaultValue"] forKey:key];
}
}
[[NSUserDefaults standardUserDefaults] registerDefaults:defaultsToRegister];
[defaultsToRegister release];
}
Here is my code based on #PCheese's answer which adds support for keys without a default value and child panes.
- (void)registerDefaultsFromSettingsBundle {
[[NSUserDefaults standardUserDefaults] registerDefaults:[self defaultsFromPlistNamed:#"Root"]];
}
- (NSDictionary *)defaultsFromPlistNamed:(NSString *)plistName {
NSString *settingsBundle = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
NSAssert(settingsBundle, #"Could not find Settings.bundle while loading defaults.");
NSString *plistFullName = [NSString stringWithFormat:#"%#.plist", plistName];
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:[settingsBundle stringByAppendingPathComponent:plistFullName]];
NSAssert1(settings, #"Could not load plist '%#' while loading defaults.", plistFullName);
NSArray *preferences = [settings objectForKey:#"PreferenceSpecifiers"];
NSAssert1(preferences, #"Could not find preferences entry in plist '%#' while loading defaults.", plistFullName);
NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:#"Key"];
id value = [prefSpecification objectForKey:#"DefaultValue"];
if(key && value) {
[defaults setObject:value forKey:key];
}
NSString *type = [prefSpecification objectForKey:#"Type"];
if ([type isEqualToString:#"PSChildPaneSpecifier"]) {
NSString *file = [prefSpecification objectForKey:#"File"];
NSAssert1(file, #"Unable to get child plist name from plist '%#'", plistFullName);
[defaults addEntriesFromDictionary:[self defaultsFromPlistNamed:file]];
}
}
return defaults;
}
Here is the Swift version:
call it from:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
self.registerDefaultsFromSettingsBundle()
return true
}
converted function:
func registerDefaultsFromSettingsBundle(){
//NSLog("Registering default values from Settings.bundle");
let defs: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defs.synchronize()
var settingsBundle: NSString = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle")!
if(settingsBundle.containsString("")){
NSLog("Could not find Settings.bundle");
return;
}
var settings: NSDictionary = NSDictionary(contentsOfFile: settingsBundle.stringByAppendingPathComponent("Root.plist"))!
var preferences: NSArray = settings.objectForKey("PreferenceSpecifiers") as NSArray
var defaultsToRegister: NSMutableDictionary = NSMutableDictionary(capacity: preferences.count)
for prefSpecification in preferences {
if (prefSpecification.objectForKey("Key") != nil) {
let key: NSString = prefSpecification.objectForKey("Key")! as NSString
if !key.containsString("") {
let currentObject: AnyObject? = defs.objectForKey(key)
if currentObject == nil {
// not readable: set value from Settings.bundle
let objectToSet: AnyObject? = prefSpecification.objectForKey("DefaultValue")
defaultsToRegister.setObject(objectToSet!, forKey: key)
NSLog("Setting object \(objectToSet) for key \(key)")
}else{
//already readable: don't touch
//NSLog("Key \(key) is readable (value: \(currentObject)), nothing written to defaults.");
}
}
}
}
defs.registerDefaults(defaultsToRegister)
defs.synchronize()
}
Swift 3 version
func registerDefaultsFromSettingsBundle(){
guard let settingsBundle = Bundle.main.path(forResource: "Settings", ofType: "bundle") else {
print("Could not locate Settings.bundle")
return
}
guard let settings = NSDictionary(contentsOfFile: settingsBundle+"/Root.plist") else {
print("Could not read Root.plist")
return
}
let preferences = settings["PreferenceSpecifiers"] as! NSArray
var defaultsToRegister = [String: AnyObject]()
for prefSpecification in preferences {
if let post = prefSpecification as? [String: AnyObject] {
guard let key = post["Key"] as? String,
let defaultValue = post["DefaultValue"] else {
continue
}
defaultsToRegister[key] = defaultValue
}
}
UserDefaults.standard.register(defaults: defaultsToRegister)
}
A Swift 2 compatible version
func registerDefaultsFromSettingsBundle(){
let defaults = NSUserDefaults.standardUserDefaults()
defaults.synchronize()
let settingsBundle: NSString = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle")!
if(settingsBundle.containsString("")){
NSLog("Could not find Settings.bundle");
return;
}
let settings = NSDictionary(contentsOfFile: settingsBundle.stringByAppendingPathComponent("Root.plist"))!
let preferences = settings.objectForKey("PreferenceSpecifiers") as! NSArray;
var defaultsToRegister = [String: AnyObject](minimumCapacity: preferences.count);
for prefSpecification in preferences {
if (prefSpecification.objectForKey("Key") != nil) {
let key = prefSpecification.objectForKey("Key")! as! String
if !key.containsString("") {
let currentObject = defaults.objectForKey(key)
if currentObject == nil {
// not readable: set value from Settings.bundle
let objectToSet = prefSpecification.objectForKey("DefaultValue")
defaultsToRegister[key] = objectToSet!
NSLog("Setting object \(objectToSet) for key \(key)")
}
}
}
}
defaults.registerDefaults(defaultsToRegister)
defaults.synchronize()
}
One more version of the same theme. I kept Lawrence Johnston's support for child panes and added the i18n/l10n support.
// This code is folklore, first created by an unknown person and copied, pasted
// and published by many different programmers, each (hopefully) of whom added
// some improvemrnts. (c) the People of the Earth
- (NSDictionary *)defaultsFromPlistNamed:(NSString *)plistName {
NSString *settingsBundlePath = [[NSBundle mainBundle] pathForResource:#"Settings" ofType:#"bundle"];
if (!settingsBundlePath) {
NSAssert(settingsBundlePath, #"Could not find Settings.bundle while loading defaults.");
return nil;
}
NSBundle *settingsBundle = [NSBundle bundleWithPath:settingsBundlePath];
if (!settingsBundlePath) {
NSAssert(settingsBundle, #"Could not load Settings.bundle while loading defaults.");
return nil;
}
NSString *plistFullName = [settingsBundle pathForResource:plistName ofType:#"plist"];
if (!plistName) {
NSAssert1(settings, #"Could not find plist '%#' while loading defaults.", plistFullName);
return nil;
}
NSDictionary *settings_dic = [NSDictionary dictionaryWithContentsOfFile:plistFullName];
if (!settings_dic) {
NSAssert1(settings_dic, #"Could not load plist '%#' while loading defaults.", plistFullName);
return nil;
}
NSArray *preferences = [settings_dic objectForKey:#"PreferenceSpecifiers"];
NSAssert1(preferences, #"Could not find preferences entry in plist '%#' while loading defaults.", plistFullName);
NSMutableDictionary *defaults = [NSMutableDictionary dictionary];
for(NSDictionary *prefSpecification in preferences) {
NSString *key = [prefSpecification objectForKey:#"Key"];
if (key) {
id value = [prefSpecification objectForKey:#"DefaultValue"];
if(value) {
[defaults setObject:value forKey:key];
NSLog(#"setting %# = %#",key,value);
}
}
NSString *type = [prefSpecification objectForKey:#"Type"];
if ([type isEqualToString:#"PSChildPaneSpecifier"]) {
NSString *file = [prefSpecification objectForKey:#"File"];
NSAssert1(file, #"Unable to get child plist name from plist '%#'", plistFullName);
if (file) {
[defaults addEntriesFromDictionary:[self defaultsFromPlistNamed:file]];
}
}
}
return defaults;
}
- (void)registerDefaultsFromSettingsBundle {
[[NSUserDefaults standardUserDefaults] registerDefaults:[self defaultsFromPlistNamed:#"Root"]];
}
Call [self registerDefaultsFromSettingsBundle]; from - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
if(x) {NSAssert(x);return nil;} looks stupid, but I feel lazy to do something about it.
A different approach: code generation
The following generates an Objective-C file with a single function that registers the defaults for Root.plist.
xsltproc settings.xslt Settings.bundle/Root.plist > registerDefaults.m
In can be run automatically using a "Run Script" build phase in XCode. The phase should be placed before "Compile Sources". (xsltproc comes with OS X.)
This is somewhat basic and doesn't handle nested files, but maybe somebody has a use for it.
settings.xslt
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="UTF-8" omit-xml-declaration="yes" indent="no" />
<xsl:template match="dict">
<xsl:choose>
<xsl:when test="key[.='DefaultValue']/following-sibling::*[position()=1 and self::true]">
#"YES",
</xsl:when>
<xsl:when test="key[.='DefaultValue']/following-sibling::*[position()=1 and self::false]">
#"NO",
</xsl:when>
<xsl:otherwise>
#"<xsl:value-of select="key[.='DefaultValue']/following-sibling::*[1]"/>",
</xsl:otherwise>
</xsl:choose>
#"<xsl:value-of select="key[.='Key']/following-sibling::*[1]"/>",
</xsl:template>
<xsl:template match="/">
void registerDefaults() {
NSDictionary *defaults =
[NSDictionary dictionaryWithObjectsAndKeys:
<xsl:apply-templates select="descendant::key[.='DefaultValue']/.."/>
nil];
[[NSUserDefaults standardUserDefaults] registerDefaults: defaults];
}
</xsl:template>
</xsl:stylesheet>
The is based on the work of Benjamin Ragheb.
A much cleaner swift 2.2 version, requires a quick extension on string to restore stringByAppendingPathComponent:
extension String {
func stringByAppendingPathComponent(path: String) -> String {
let nsSt = self as NSString
return nsSt.stringByAppendingPathComponent(path)
}
}
func registerDefaultsFromSettingsBundle() {
guard let settingsBundle = NSBundle.mainBundle().pathForResource("Settings", ofType: "bundle") else {
log.debug("Could not find Settings.bundle")
return
}
let settings = NSDictionary(contentsOfFile: settingsBundle.stringByAppendingPathComponent("Root.plist"))!
let preferences = settings["PreferenceSpecifiers"] as! NSArray
var defaultsToRegister = [String: AnyObject]()
for prefSpecification in preferences {
guard let key = prefSpecification["Key"] as? String,
let defaultValue = prefSpecification["DefaultValue"] else {
continue
}
defaultsToRegister[key] = defaultValue
}
NSUserDefaults.standardUserDefaults().registerDefaults(defaultsToRegister)
}