开发者

Best way to split and convert url params into string values

开发者 https://www.devze.com 2022-12-17 16:16 出处:网络
I would like to split a custom url for app opening in iPhone into values, my scheme w开发者_C百科ould be something like:

I would like to split a custom url for app opening in iPhone into values, my scheme w开发者_C百科ould 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?


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];


Use Google's gtm_dictionaryWithHttpArgumentsString NSDictionary category

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消