IOS stringWithContentsOfURL返回null
以下是我的一段代码:IOS stringWithContentsOfURL返回null,ios,null,webkit,Ios,Null,Webkit,以下是我的一段代码: NSString * escAddress = [fromLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; //1 NSString * request = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", escAdd
NSString * escAddress = [fromLocation stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]; //1
NSString * request = [NSString stringWithFormat:@"http://maps.google.com/maps/api/geocode/json?sensor=false&address=%@", escAddress]; //2
NSLog(@"%@", request); //3
NSString * result = [NSString stringWithContentsOfURL:[NSURL URLWithString:request] encoding:NSUTF8StringEncoding error:nil]; //4
NSLog(@"%@", result); //5
第3行的输出正确。内容如下:
http://maps.google.com/maps/api/geocode/json?sensor=false&address=stack%20overflow%20.%20com
如果escAddress中的字符串为“stack overflow.com”
问题似乎在第四行。我不知道为什么,但它总是返回空值。我可以从第3行的输出中复制并粘贴URL,将其粘贴到我的浏览器中,然后获得我需要的相关信息。那它为什么不把它放进绳子里呢?我以前使用过这个方法,现在我已经更新到Xcode 6,它停止了。如果地址格式不正确,服务将返回:“NSCocoaErrorDomain Code=262”,等等。。如果它是一个正确的街道地址,而不是域地址,则它可以工作。我查了一下我的街道地址,用
%20
替换了所有的空格,结果成功了。如果我未能替换空格,则得到错误代码262
我所说的街道地址是指(例如):100主街,Anytown,ST ZCode
编码为:
100%20Main%20Street、%20Anytown、%20ST%20zcode
http://maps.google.com/maps/api/geocode/json?sensor=false&address=100%20Main%20Street,%20Anytown,%20ST%20ZCcode
结果证明这不是程序,也不是防火墙。这是Xcode或模拟器。同时退出,重新打开。之后工作得很好。因为它是在升级到Xcode 6之后才启动的,所以我觉得有些东西已经改变了。哦,好吧。不知道为什么会这样。但它仍在工作。使用
error
参数查看问题所在。NSError*error=nil;NSString*result=[NSString stringWithContentsOfURL:[NSURL URLWithString:请求]编码:NSUTF8STRING编码错误:&错误]//4
Error Domain=nscocaerorrordomain code=256“操作无法完成。(Cocoa错误256)。”UserInfo=0x7fa491ce1e70{NSURL=}顺便问一下-为什么要将“stack overflow.com”作为映射的地址传递?这里使用这个示例,因为我在stackoverflow.com上。我认为在上面写一个实际地址是不相关的。我所演示的就是实际的编码工作。很明显,我在运行程序时使用的是真实地址搜索。