Here’s a little utility function I use to decode application/x-www-form-urlencoded
strings on the iPhone:
- (NSDictionary*)extractArguments:(NSString*)raw
{
NSArray* args = [raw componentsSeparatedByString:@"&"];
NSMutableDictionary* rv = [NSMutableDictionary dictionaryWithCapacity:[args count]];
for (NSString* sPair in args)
{
NSArray* aPair = [sPair componentsSeparatedByString:@"="];
NSString* k = [aPair count]>0?[aPair objectAtIndex:0]:@"";
NSString* v = [aPair count]>1?[aPair objectAtIndex:1]:@"";
k = [[k stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
v = [[v stringByReplacingOccurrencesOfString:@"+" withString:@" "] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
if ([k length])
{
NSMutableArray* vs = [rv objectForKey:k];
if (vs)
{
[vs addObject:v];
}
else
{
[rv setObject:[NSMutableArray arrayWithObject:v] forKey:k];
}
}
}
return rv;
}
The return value is an NSDictionary
that maps NSString
keys to NSArray
values. The values are NSArrays
because under form encoding more than one value may be associated with a key. The value NSArrays
contain NSStrings
.