Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fatal error: unexpectedly found nil while unwrapping an Optional value, Get json error swift

enter image description here

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
}
like image 209
小弟调调 Avatar asked Dec 30 '25 17:12

小弟调调


1 Answers

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.

like image 73
Kreiri Avatar answered Jan 01 '26 07:01

Kreiri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!