How does one append something like "?x=123" to an NSURL?

ios

Solution

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);
}

Problem

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" ?

Original source