views:

182

answers:

3

Hi

I would like to split a custom url for app opening in iPhone into values, my scheme would be something like:

appname://user=jonsmith&message=blah%20blah

Where I would like to be able to get "user" and "message" as two NSStrings. Any advice on best approach?

A: 
NSString* yourString = @"appname://user=jonsmith&message=blah%20blah";
NSString* queryString = [yourString substringFromIndex:strlen("appname://")];
NSArray* queryArray = [queryString componentsSeparatedByString:@"&"];
NSMutableDictionary* queryDict = [NSMutableDictionary dictionary];
for (NSString* query in queryArray) {
    NSUInteger indexOfEqualsSign = [query rangeOfString:@"="].location;
    if (indexOfEqualsSign != NSNotFound) {
       NSString* key = [[query substringToIndex:indexOfEqualsSign] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       NSString* value = [[query substringFromIndex:indexOfEqualsSign+1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
       [queryDict setObject:value forKey:key];
    }
}
return queryDict;

Use an NSScanner if you need to save more memory.

KennyTM
+4  A: 

Assuming your url is in an NSURL object called url:

NSMutableDictionary *queryParams = [[NSMutableDictionary alloc] init];
NSArray *components = [[url query] componentsSeparatedByString:@"&"];

for (NSString component in components) {
    NSArray *pair = [component componentsSeparatedByString:@"="];

    [queryParams setObject:[[pair objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding: NSMacOSRomanStringEncoding]
                    forKey:[pair objectAtIndex:0]]; 
}

...

[queryParams release];
Frank Schmitt
+1 this is how I'd do it.
Dave DeLong
KennyTM
thank you, this seems like the lowest cost - is there a quick way to reverse url encode the %20 etc?
mootymoots
I can have my url do as you suggest with the ? query, that's fine :)
mootymoots
Just edited to add the `stringByReplacingPercentEscapesUsingEncoding:` call
Frank Schmitt
@mootymoots: This solution already has escaped the %20.
KennyTM
Note that this doesn't handle any GET parameters that don't have both a key and a value, eg. `http://foo.com?asd`. It will raise an exception when you do `[pair objectAtIndex:1]`.
zekel
A: 

Use Google's gtm_dictionaryWithHttpArgumentsString NSDictionary category

http://code.google.com/p/google-toolbox-for-mac/source/browse/trunk/Foundation/GTMNSDictionary%2BURLArguments.h

Ford