fatal error: unexpectedly found nil while unwrapping an Optional value in Swift when tried to parse JSON

前端 未结 3 2154
梦如初夏
梦如初夏 2021-01-25 17:18

I\'ve tried to build up a document-based Cocoa app and when I tried to parse JSON in readFromData: ofType: error: method, I got an error: fatal error: unexpec

3条回答
  •  灰色年华
    2021-01-25 17:56

    If the data does not contain a valid JSON object, the JSONObjectWithData function will return a nil, so you need to do a conditional unwrapping as follows:

    if let dict = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: jsonError) as? NSDictionary {
        println("Dictionary: \(dict)")
    } else {
       println("nil")
       let resultString = NSString(data: data, encoding: NSUTF8StringEncoding)
       println("Flawed JSON String: \(resultString)")
    }
    

    I hope it helps..... e

提交回复
热议问题