Swift, NSJSONSerialization and NSError

后端 未结 5 1346
-上瘾入骨i
-上瘾入骨i 2021-02-12 16:19

The problem is when there is incomplete data NSJSONSerialization.JSONObjectWithData is crashing the application giving unexpectedly found nil while unwrappin

5条回答
  •  旧巷少年郎
    2021-02-12 17:05

    Updated for Swift 3

    let jsonData = Data()
    do {
        let jsonObject = try JSONSerialization.jsonObject(with: jsonData, options:JSONSerialization.ReadingOptions(rawValue: 0))
        guard let dictionary = jsonObject as? Dictionary else {
            print("Not a Dictionary")
            // put in function
            return
        }
        print("JSON Dictionary! \(dictionary)")
    }
    catch let error as NSError {
        print("Found an error - \(error)")
    }
    

    Swift 2

    let JSONData = NSData()
    do {
        let JSON = try NSJSONSerialization.JSONObjectWithData(JSONData, options:NSJSONReadingOptions(rawValue: 0))
        guard let JSONDictionary: NSDictionary = JSON as? NSDictionary else {
            print("Not a Dictionary")
            // put in function
            return
        }
        print("JSONDictionary! \(JSONDictionary)")
    }
    catch let JSONError as NSError {
        print("\(JSONError)")
    }
    

提交回复
热议问题