I had been using the following line of code to parse JSON data in Objective-C, but the same in Swift crashes the app.
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:_webData
options:kNilOptions
error:&error];
I tried using NSJSONReadingOptions.MutableContainers
but doesn't seem to work. I have verified the validity of the JSON data obtained from the web server using various JSON validity checkers found online.
[EDIT] The swift code I am using is as follows:
let jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary
[UPDATE]
Using let jsonResult: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
solves the issue.
The error Xcode is giving you isn't very helpful, but it looks like you need to declare your error
variable a different way (more at Apple's documentation), and then make sure you handle the case of the dictionary coming back nil
:
var error: AutoreleasingUnsafePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data,
options:NSJSONReadingOptions.MutableContainers,
error: error) as? NSDictionary
if jsonResult {
// process jsonResult
} else {
// couldn't load JSON, look at error
}
All answers didn't work for me. This worked (21.01.2015 - Xcode 6.1.1 / iOS 8.1.2):
var err: AutoreleasingUnsafeMutablePointer<NSError?> = nil
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions.MutableContainers, error:err) as NSDictionary
Found it here: Use of undeclared type AutoreleasingUnsafePointer Xcode 6 beta 6
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With