2015-05-01 43 views
0

我在最新版本的Xcode,我得到这个错误:“从'NSData'投射?'无关型 '的NSDictionary' 总是失败”Swift - 从'NSData'投射?到无关的类型'NSDictionary'总是失败

与此代码:

let dataObject = NSData(contentsOfURL: location) 

let weatherDictionary: NSDictionary = NSJSONSerialization.dataWithJSONObject(dataObject!, options: nil, error: nil) as! NSDictionary 

编程语言:雨燕

更新的代码:

if (error == nil) { 
       let dataObject = NSData(contentsOfURL: location) 

       let weatherDictionary: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject!, options: nil, error: nil) as! NSDictionary 

       } 
  • 得到一个断点现在,当我运行我的应用。

对不起,我还是新堆栈溢出

+0

是的,它是NSDictionary –

+0

'let weatherDictionary:AnyObject! = NSJSONSerialization.JSONObjectWithData(dataObject,options:NSJSONReadingOptions.MutableContainers,error:nil)'使用此代码并检查'weatherDictionary'是'NSArray'或'NSDictionary'。 –

+0

仍然出错 –

回答

2

当然失败中。你正在调用错误的方法。

NSJSONSerialization方法dataWithJSONObject接受一个可以转换为JSON并返回NSData的对象。它将始终返回NSData(或无)。在任何情况下,它都不会返回字典。

如果您有要转换为集合对象的NSData,那么您希望使用方法JSONObjectWithData来代替。

+0

let dataObject = NSData(contentsOfURL:location) let weatherDictionary:NSDictionary = NSJSONSerialization.JSONObjectWithData(dataObject !, options:nil,error:nil)as! NSDictionary 它仍然无法正常工作 –

相关问题