How to add something like "? X = 123" to NSURL?

I have NSURL forms

"http://abc.def.com:1234/stuff/"

and I want to add to it so that the final url is as follows

"http://abc.def.com:1234/stuff/?x=123".

But if I do it

url = [NSURL URLWithString:@"http://abc.def.com:1234/stuff/?"];
url = [url URLByAppendingPathComponent:@"x=123"];

Then the result

http://abc.def.com:1234/stuff/x=123?

(this is the same result if URLByAppendingPathExtension is used).

But if I do it

url = [NSURL URLWithString:@"http://abc.def.com:1234/stuff/?"];
url = [url URLByAppendingPathComponent:@"x=123"];

Then the result

http://abc.def.com:1234/stuff/%3Fx=123

(also the same result if URLByAppendingPathExtension is used).

None of them are what I do. How to get the final result "http://abc.def.com:1234/stuff/?x=123"?

+5
source share
2 answers

I think the simplest answer here is to create a new URL using the old 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);
}
+8
source

NSURL last, NSString, :

NSString *urlString = @"http://www.site.com/";
if (some condition)
    urlString = [urlString stringByAppendingString:@"?x=123"];

NSURL *url = [NSURL URLWithString:urlString];
+5

All Articles