【问题标题】:Accesing https json api returns nil each time (Swift)访问 https json api 每次都返回 nil (Swift)
【发布时间】:2014-09-02 18:50:11
【问题描述】:

我试图在 Swift 中使用此代码访问 Flickr api,当我打印 jsonData 变量时,它以二进制格式打印数据

 var error = NSError()
 var api_url = NSURL.URLWithString("https://api.flickr.com/services/rest/?&method=flickr.photos.search&tags=car&api_key=xxxxxxxxxxxxx&format=json")
 let jsonData: NSData = NSData.dataWithContentsOfURL(api_url, options: nil, error: nil)
 let result:NSDictionary = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: nil) as NSDictionary
 return result

但我的应用程序在结果变量上崩溃 致命错误:在展开可选值时意外发现 nil 帮助!非常感谢。

【问题讨论】:

  • 如果 dataWithContentsOfURL 失败,它将返回 nil。我会首先尝试使用您拥有的那个错误对象,如果您确定数据为零,看看是否有任何错误。
  • 但是错误来自结果变量而不是来自jsonData变量,仔细检查我打印了jsonData并且它不是空的。
  • 那么如何将错误对象用于 NSJSONSerialization?看起来你有那个错误对象,但没有将它用于任何事情......使用那个东西! :)

标签: ios xcode swift


【解决方案1】:

这是 Flickr API 的默认行为。 JSON 响应带有回调函数包装器。

要禁用它,请在您的网址末尾添加&nojsoncallback=1

官方文档: https://www.flickr.com/services/api/response.json.html

由于原始 JSON 是用函数包装器包装的,因此您的 NSJSONSerialization 返回 nil。

【讨论】:

    猜你喜欢
    • 2014-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-09
    • 1970-01-01
    • 2017-10-07
    • 2015-08-21
    相关资源
    最近更新 更多