我努力學習斯威夫特和我有了解了一塊有關處理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
它仍然失敗,「預期類型後」爲'。
通過'http://api.worldweatheronline.com/free/v2/marine.ashx鍵= 45e8e583134b4371a2fa57a9e5776&FORMAT = XML&Q = 45,-2'返回XML,不是JSON。 – Can 2015-03-03 00:39:25