PDA

View Full Version : Encoding a URL




MarcVanH
Dec 12, 2008, 02:01 PM
I am having the toughest time encoding a URL that contains a query string.

What I want to do is open a webbrowser control to a URL. I've done this several times before with no problems. Only difference this time - the URL has a query string on the end.

http://my.host.com/path?address=123 Main Street

Now, of course, "123 Main Street" needs to be encoded first. This is where I am having the trouble.

The following example code illustrates my problem:

NSString *myUrl = [@"123 main St" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSLog(myUrl);

I would expect the output to be "123%20main%20St". But instead, the output is garbage.

Can anyone tell me why this is? Is this a bug?



fenrus110
Dec 12, 2008, 02:03 PM
try adding retain to it.

or alloc init the string, then do the encoding.

MarcVanH
Dec 12, 2008, 02:24 PM
Thanks for the suggestions - but unfortunately neither worked. Still garbage out.

Scratch75
Dec 12, 2008, 03:19 PM
Your URL encoding is working just fine...it's your call to NSLog that's causing you pain.

Try this instead:

NSLog(@"%@", myUrl);

fenrus110
Dec 12, 2008, 03:57 PM
oh yeah... i remember the pain of me forgetting to put the @ symbol back in the day.

xsmasher
Dec 12, 2008, 08:38 PM
try adding retain to it.

or alloc init the string, then do the encoding.

Side note on this - you can't "alloc init the string, then do the encoding." You can not change a string at all once it is created - you can create new strings, but you can't change an existing one.

MarcVanH
Dec 15, 2008, 12:24 PM
Thanks very much. I feel a little silly.


Your URL encoding is working just fine...it's your call to NSLog that's causing you pain.

Try this instead:

NSLog(@"%@", myUrl);