2016-11-16 219 views
0

我使用下面的代碼:如何在swift 3中處理錯誤?

let jsonData1 = (try? Data(contentsOf: URL(string: "\(label2)")!)) as Data! 
    var error : NSError? 
    let ReadableJSON1 = JSON (data:jsonData1!, options: JSONSerialization.ReadingOptions.mutableContainers, error: nil) 


    if (error != nil){ 

     let myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert) //you can change message to whatever you want. 
     let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil) 
     myAlert.addAction(okAction) 
     self.present(myAlert, animated: true, completion: nil) 

     return 
    } 

如果應用程序打開JSON文件形成鏈接時發現錯誤,應該顯示一個警告給用戶。目前它正在崩潰,看起來這些操作沒有執行,這就是爲什麼我沒有看到警報。你能幫我解決這個問題嗎? enter image description here

+0

你沒有使用'try'' catch'的原因?機制? – Honey

+0

如何? – Dakata

+1

由於Swift 2.2,(NS)錯誤使用try/catch進行管理:https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html – Larme

回答

0

試試這個代碼:

var json : [String: AnyObject]? // Property 
do { 
    let jsonData1 = (try? Data(contentsOf: URL(string: "\(label2)")!)) as Data! 
    json = try JSONSerialization.jsonObject(with: jsonData1, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: AnyObject] 
} 
catch let error as NSError { 
    let myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .alert) //you can change message to whatever you want. 
    let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil) 
    myAlert.addAction(okAction) 
    self.present(myAlert, animated: true, completion: nil) 

    return 
} 

希望這將有助於!快樂編碼!

+0

我應該在哪裏使用該代碼,因爲我沒有看到如何在這裏讀取json鏈接 – Dakata

+0

好吧,您需要讀取do {}塊內的響應數據。我編輯了答案。請檢查 – iProgrammer

+0

它不起作用:( – Dakata