1
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL(string: "https://api.forecast.io/forecast/MYKEYHERE/")
let session = NSURLSession.sharedSession()
let task: NSURLSessionDownloadTask = session.downloadTaskWithURL(url!, completionHandler: { (location: NSURL!, response: NSURLResponse!, error: NSError!) -> Void in
if error == nil {
let data = NSData(contentsOfURL: location)
let json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error: nil) as! NSDictionary!
println(json)
}
})
task.resume()
}
這是爲天氣API下載任務的代碼。只是想知道爲什麼我得到的錯誤:爲什麼我的代碼在線程6中運行時崩潰了:NSOperationQueue?
Thread 6: EXC_BAD_INSTRUCTION(code=EXC_1386_INVOP, subcode=0x0).
非常感謝。
感謝Rob,這非常有幫助。但我只是想知道,當你說使用錯誤參數時,我認爲你指的是可選的'var error:NSError?'的initalisation,但你爲什麼要這樣做?該錯誤是否已經在完成處理程序中初始化? –
有兩個錯誤對象:有一個與網絡請求相關聯,但還有'JSONObjectWithData'的'error'參數。我擔心後者。如果網絡請求成功(即,沒有'NSError'對象被傳遞給閉包),您仍然需要一些變量來保存JSON解析生成的任何錯誤。 – Rob