2015-05-01 66 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 它仍然無法正常工作 –

相關問題