【问题标题】:IOS stringWithContentsOfURL returning nullIOS stringWithContentsOfURL 返回 null
【发布时间】: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 上。我认为在那里放一个实际地址并不重要。实际的编码工作就是我所展示的。我显然在运行程序时使用了真实地址搜索。

标签: ios null webkit


【解决方案1】:

如果地址格式错误,服务会返回:“NSCocoaErrorDomain Code=262”等。如果它是正确的街道地址,而不是域地址,它可以工作。我查找了我的街道地址,用%20 替换了所有空格,它起作用了。如果我未能替换空格,则会收到错误代码 262。

我的意思是街道地址(示例):
100 Main Street, Anytown, ST ZCode
编码为:
100%20Main%20Street,%20Anytown,%20ST%20ZCcode

http://maps.google.com/maps/api/geocode/json?sensor=false&address=100%20Main%20Street,%20Anytown,%20ST%20ZCcode

【讨论】:

    【解决方案2】:

    原来不是程序,也不是防火墙。它是 Xcode 或模拟器。两者都退出,重新打开。之后工作正常。因为它是在更新到 Xcode 6 后才开始的,所以我认为有些东西已经改变了。那好吧。不知道为什么会这样。不过它的工作原理。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多