2015-03-03 116 views
2

我努力學習斯威夫特和我有了解了一塊有關處理JSON並獲得掙扎處理JSON「致命錯誤:意外發現零而展開的可選值」使用此代碼:在斯威夫特

import UIKit 

class ViewController: UIViewController { 

@IBOutlet weak var webView: UIWebView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let urlPath = "http://api.worldweatheronline.com/free/v2/marine.ashx?key=45e8e583134b4371a2fa57a9e5776&format=xml&q=45,-2" 
    let url: NSURL = NSURL(string: urlPath)! 
    let session = NSURLSession.sharedSession() 

    let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in 
     println("Task completed") 
     if ((error) != nil) { 
      println(error) 

     } else { 
      var err: NSError? 
      println("URL: \(url)") 

      var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary 

      println(jsonResult) 
     } 


    }) 

    task.resume() 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


} 

我使用的API密鑰是免費的,所以不用擔心使用它。 JSON的結果應該something like this但我不是與問候:

Task completed  
URL: http://api.worldweatheronline.com/free/v2/marine.ashx?key=45e8e583134b4371a2fa57a9e5776&format=xml&q=45,-2 
fatal error: unexpectedly found nil while unwrapping an Optional value 

我假設jsonResult變量是什麼導致了問題,但即使我嘗試強行解開它(我認爲這就是我什麼)類似的東西

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary 

它仍然失敗,「預期類型後」爲'。

+1

通過'http://api.worldweatheronline.com/free/v2/marine.ashx鍵= 45e8e583134b4371a2fa57a9e5776&FORMAT = XML&Q = 45,-2'返回XML,不是JSON。 – Can 2015-03-03 00:39:25

回答

1

一切都失效能在這裏,一個網站甚至可以返回200,但返回任何結果,數據可以來損壞,並且,在你的情況,我想叫你正在使用的URL和發現,它實際上是XML,所以...有你的問題嗎?

一個更可靠的方法(假設你仍然要解析JSON,也許從其他網站?The ISS has an open API)是使用if let解開自選,然後在其他情況下處理錯誤,而不是!自己的方式成功。

這裏是一個非常廣泛的一切檢查

task = session.dataTaskWithRequest(NSURLRequest(URL: url), completionHandler: { [unowned self] (data, response :NSURLResponse!, errorRequest) -> Void in 
    // Check the HTTP Header 
    if let responseHTTP = response as? NSHTTPURLResponse 
    { 
     if responseHTTP.statusCode != 200 
     { 
      println("Received status code \(responseHTTP.statusCode)") 
      return 
     } 
    } 
    else 
    { 
     println("Non-HTTP Response received") 
     return 
    } 

    var errorParsing : NSError? 

    if let JSON = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: &errorParsing) as? NSDictionary 
    { 
     // Do the parsing 
    } 
    else 
    { 
     println("Error parsing: \(errorParsing)") 
    } 
}) 

task!.resume() 
+0

聖牛。是的,這個問題肯定與我試圖將XML解析爲JSON的事實有關。 http://api.worldweatheronline.com/free/v2/marine.ashx?key=45e8e583134b4371a2fa57a9e5776&format=json&q=45,-2有效! – kevingduck 2015-03-03 03:22:41

1

NSJSONSerialization.JSONObjectWithData...返回可選NSData?。這意味着你不能直接將它投射到NSDictionary。要解決崩潰,你將需要使用?as這意味着你的jsonResult要麼是NSDictionarynil

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) ?as NSDictionary

在你的情況,你可以放心地通過這樣解開可選。

var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil)

if let jsonResult = jsonResult ?as NSDictionary { 
println(jsonResult) 
}