
Get json error
I am getting the error fatal error: unexpectedly found nil while unwrapping an Optional value when I try to return the json:
func getJson (str:NSString) -> AnyObject{
var proxiesURL = NSURL(string:str)
var proxiesDataJson = NSData.dataWithContentsOfURL(proxiesURL, options: NSDataReadingOptions.DataReadingUncached, error: nil)
var json: AnyObject!
if (proxiesDataJson != nil ){
json = NSJSONSerialization.JSONObjectWithData(proxiesDataJson, options: NSJSONReadingOptions.AllowFragments, error: nil) as AnyObject
}
return json
}
I assume the question is "what am I doing wrong".
Your function returns AnyObject (non-optional, thus cannot be nil). You declared json as AnyObject! (implicitly unwrapped optional - it may be nil, but you promise to compiler that it will have non-nil value). And yet json is nil when you attempt to return it - either code at json = NSJSONSerialization.JSONObjectWithData line wasn't executed, or NSJSONSerialization.JSONObjectWithData returned nil.
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