Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ios

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

like image 814
Gruntcakes Avatar asked Apr 24 '12 19:04

Gruntcakes


2 Answers

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);
}
like image 183
Jeffery Thomas Avatar answered Nov 05 '22 21:11

Jeffery Thomas


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];
like image 43
Mark Granoff Avatar answered Nov 05 '22 22:11

Mark Granoff