Best way to split and convert url parameters to string values

I would like to split the user url to open the application on the iPhone in values, my scheme would be something like this:

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

Where I would like to receive the "user" and the "message" as two NSStrings. Any tips on the best approach?

+6
objective-c iphone
source share
3 answers

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]; 
+6
source share

Use the Google gtm_dictionaryWithHttpArgumentsString category NSDictionary

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

+1
source share
 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 NSScanner if you need to save more memory.

-one
source share

All Articles