So I have a NSString with a url like this:
NSString stringWithFormat:@"/reading.php?title=blah&description="blah"&image_url=blah... "
what is the best way to append query string to this string? is there a dictionary kind of way to do this?
So I have a NSString with a url like this:
NSString stringWithFormat:@"/reading.php?title=blah&description="blah"&image_url=blah... "
what is the best way to append query string to this string? is there a dictionary kind of way to do this?
What you want to do is this.
[NSString stringWithFormat:@"/reading.php?title=blah&description=%@&image_url=blah... ",blah];
How about a category?
This is not great but for a first pass should give you something to get started
@interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
@end
@implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:@"%@=%@&", key, obj];
}];
return [params copy];
}
@end
This would end up with something like:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:@"42", @"special_number", @"value", @"another", nil];
NSString *myString = [NSString stringWithFormat:@"/reading.php?%@", [params URLParamsValue]];
NSLog(@"%@", myString);
#=> 2012-03-20 23:54:55.855 Untitled[39469:707] /reading.php?another=value&special_number=42&
You can use something like:
NSString *parameter1 = @"blah";
NSString *parameter2 = @"anotherblah";
NSString *fullURL = [NSString stringWithFormat:@"/reading.php?title=%@&image_url=%@", parameter1, parameter2];
You can add as many parameters as you want. Use "%@" where you will be dynamically adding the text.
Good luck :)
Copy pasting from Paul.s - which is the correct answer, imo - and fixing a (most likely inconsequential) problem of a dangling ampersand...
@interface NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
@end
@implementation NSDictionary (ps_additions)
- (NSString *)ps_URLParamsValue;
{
if (!self.count) return @"";
NSMutableString *params = [NSMutableString string];
[self enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop){
[params appendFormat:@"%@=%@&", key, obj];
}];
// return everything except that last ampersand
return [[params copy] substringToIndex:[params length]-1];
}
@end
lastObject call outside of the loop as it's not going to change.NSRangeException