Swift, NSJSONSerialization and NSError

后端 未结 5 1271
-上瘾入骨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:22

    Here is a Swift 2 extension you can use to deserialise only an NSDictionary:

    extension NSJSONSerialization{
        public class func dictionaryWithData(data: NSData, options opt: NSJSONReadingOptions) throws -> NSDictionary{
            guard let d: NSDictionary = try self.JSONObjectWithData(data, options:opt) as? NSDictionary else{
                throw NSError(domain: NSURLErrorDomain, code: NSURLErrorCannotParseResponse, userInfo: [NSLocalizedDescriptionKey : "not a dictionary"])
            }
            return d;
        }
    }
    

    Sorry I wasn't sure how to do a guard return to avoid creating the temporary 'd'.

提交回复
热议问题