是| 管道角色制作URLWithString:失败?

use*_*951 3 objective-c nsurl

我有这个非常简单的代码:

PO(URLString);
url = [NSURL URLWithString:URLString];
PO(url);
NSData * data=[NSData dataWithContentsOfURL:url];
Run Code Online (Sandbox Code Playgroud)

(PO()是我打印东西的宏.)

它大部分时间都有效.这是输出:

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&center=-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)

如您所见,它适用于http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg并且在http://maps.googleapis.com/maps/api/staticmap?&zoom上失败= 16&尺寸= 160×160&地图类型=路标&传感器=真中心= -6.187900,106.775429&标记=大小:小|颜色:蓝| -6.187900,106.775429

也许问题是| 在Google网址中.那我该怎么办呢?

Jos*_*ell 6

你是对的,|("管道")就是问题所在.

苹果文档的URLWithString:说,相关的外部文档是的RFC 23961738.据他们说,这|是一个"不安全"的角色,必须始终用URL编码.它的编码是%7C.

您可以手动更正字符串中的管道(如果它是硬编码的字符串),但更好的解决方案是使用替换它们和任何其他有问题的字符-[NSString stringByAddingPercentEscapesUsingEncoding:].