views:

1392

answers:

1

Hello,

I have code similar to the following with a URL like this... If I use the first *url, webpage will return null. If I put this URL into a URL shortening system like bit.ly it does work and returns the pages HTML as a string. I can only think I have invalid characters in my first *url? Any ideas?

NSString *url =@"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";

//above *url does not work, one below does
NSURL *url =[NSURL URLWithString: @"http://bit.ly/shortened"];
NSString *webpage = [NSString stringWithContentsOfURL:url];
+1  A: 

You probably need to escape some characters in the first URL, as follows:

NSString *url =@"http://www.testurl.com/testing/testapp.aspx/app.detail/params.frames.y.tpl.uk.item.1.cm_scid.TB-test/left.html.|metadrill,html/walk.yah.ukHB?cm_re=LN-_-OnNow-_-TestOne";
NSString *escapedURL = [url stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
NSString *webpage = [NSString stringWithContentsOfURL:[NSURL URLWithString:escapedURL]];

The construction of the URL and its fetch will fail if the URL contains characters that aren't escaped properly (looking at your URL, it's probably the pipe (|), question mark, or underscore).

Tim
Thanks Tim, worked great! What do you mean be "escaped"?
Lee Armstrong
An "escaped" character is represented by the hex code that translates to the character, rather than the character itself. For example, in URLs a space is properly represented by its "escaped" hex representation %20. The % indicates to the server that a character is escaped, and the next two characters are treated as hex and converted on the server side back to the appropriate unescaped character. It's a way of transmitting unusual characters (pipes, etc.) reliably.
Tim