【发布时间】:2014-12-17 00:54:33
【问题描述】:
这是我拥有的一段代码:
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中的字符串是“stackoverflow.com”。
问题似乎在第 4 行。我不知道为什么,但它一直返回 null。我可以从第 3 行的输出中复制并粘贴 URL,将其粘贴到我的浏览器中,然后我会得到我需要的相关信息。那么为什么不把它放到字符串中呢?我以前用过这个方法,现在我更新到 Xcode 6 就停止了。
【问题讨论】:
-
使用
error参数查看问题所在。 -
NSError *error = nil; NSString * result = [NSString stringWithContentsOfURL:[NSURL URLWithString:request] encoding:NSUTF8StringEncoding error:&error]; //4 -
Error Domain=NSCocoaErrorDomain Code=256 "操作无法完成。(Cocoa 错误 256.)" UserInfo=0x7fa491ce1e70 {NSURL=maps.google.com/maps/api/geocode/…}
-
顺便说一句 - 你为什么将“堆栈溢出 .com”作为地图的地址传递?
-
这是这里使用的示例,因为我在 stackoverflow.com 上。我认为在那里放一个实际地址并不重要。实际的编码工作就是我所展示的。我显然在运行程序时使用了真实地址搜索。