I have this very simple code:
PO(URLString);
url = [NSURL URLWithString:URLString];
PO(url);
NSData * data=[NSData dataWithContentsOfURL:url];
(PO()
is my macro to print stuff.)
It works most of the time. Here is the output:
2012-10-08 11:39:28.187 BadgerNew[2475:5007] <0x1f5321f0 BGCRBusinessForDisplay.m:(113)> URLString: http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:28.193 BadgerNew[2475:5007] <0x1f5321f0 BGCRBusinessForDisplay.m:(115)> url: http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:30.191 BadgerNew[2475:6b03] <0x1f529f00 BGCRBusinessForDisplay.m:(113)> URLString: http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true¢er=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
2012-10-08 11:39:30.196 BadgerNew[2475:6b03] <0x1f529f00 BGCRBusinessForDisplay.m:(115)> url: (null)
As you see, it works fine for http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg and it fails on http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true¢er=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
Perhaps the issue is the | in the Google URL. So what should I do with it?
You're right, the |
(the "pipe") is the problem.
The Apple docs for URLWithString:
say that the relevant external docs are RFCs 2396 and 1738. According to them, |
is an "unsafe" character and must always be encoded in a URL. The encoding for it is %7C
.
You can correct the pipes in your string manually (if it is a hard-coded string), but the better solution would be to replace them and any other problematic characters using -[NSString stringByAddingPercentEscapesUsingEncoding:]
.