I have an NSURL of the form
"http://abc.def.com:1234/stuff/"
and I want to append to it so the final url is like this
"http://abc.def.com:1234/stuff/?x=123".
But if I do this
url = [NSURL URLWithString:@"http://abc.def.com:1234/stuff/?"];
url = [url URLByAppendingPathComponent:@"x=123"];
Then the result is
http://abc.def.com:1234/stuff/x=123?
(its the same result if URLByAppendingPathExtension is used).
But if I do this
url = [NSURL URLWithString:@"http://abc.def.com:1234/stuff/?"];
url = [url URLByAppendingPathComponent:@"x=123"];
Then the result is
http://abc.def.com:1234/stuff/%3Fx=123
(also the same result if URLByAppendingPathExtension is used).
Neither of which is what I am after. How do I get a final result of "http://abc.def.com:1234/stuff/?x=123" ?
I think the simplest answer here is to create a new URL using the old one as the base URL.
url = [NSURL URLWithString:@"?x=123" relativeToURL:url]
Here is a unit test that checks the logic
- (void)testCreatingQueryURLfromBaseURL
{
NSURL *url = [NSURL URLWithString:@"http://foo.com/bar/baz"];
url = [NSURL URLWithString:@"?x=1&y=2&z=3" relativeToURL:url];
STAssertEqualObjects([url absoluteString], @"http://foo.com/bar/baz?x=1&y=2&z=3", nil);
}
Create your actual NSURL
object last, from an NSString
that you build up as needed:
NSString *urlString = @"http://www.site.com/";
if (some condition)
urlString = [urlString stringByAppendingString:@"?x=123"];
NSURL *url = [NSURL URLWithString:urlString];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With