Swift Try/Catch JSON

Posted in :

這個範例很實用,幾乎call server API 都是傳回 json, 如果遇到 server side 有異常的時候,使用 try catch 的方法如下。

 

範例1號:

do {
   let responseJSON = try JSONSerialization.jsonObject(with: data,   options: []) as! [[String: Any]]
   completion(responseJSON)
   } catch {
   print(“Hm, something is wrong here. Try connecting to the wifi.“)
   }

 


範例2號:

The dotrycatch process catches errors that are thrown, but is not a generalized exception handling process. As before, as a developer, you are still responsible for preventing exceptions from arising (e.g. the forced unwrapping of the optional NSData).

So, check to make sure data is not nil before proceeding. Likewise, don’t use as! in the cast unless you are assured that the cast cannot fail. It is safer to guard against data being nil and perform an optional binding of the JSON to a dictionary:

let task = URLSession.sharedSession().dataTaskWithURL(url!) { data, response, error in
    guard data != nil else {
        print(error)
        return
    }

    do {
        if let z = try JSONSerialization.JSONObjectWithData(data!, options:[]) as? [String: AnyObject] {
            // do something with z
        }
    } catch let parseError {
        print(parseError)
    }
}
task.resume()

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *