-->

unexpectedly found nil while unwrapping an Optiona

2020-07-26 20:14发布

问题:

im working on WKWebView and when i load a url without parameters like this it works fine

func loadAddress(lat:Double,lng:Double){
    let requestURL = NSURL(string:"http://url.com/dev2/billboard/geo")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.load(request as URLRequest)
}

but i want to send user's location with get parameters like this

func loadAddress(lat:Double,lng:Double){
    let requestURL = NSURL(string:"http://url.com/dev2/billboard/geo/\(lat)/\(lng)")
    let request = NSURLRequest(url: requestURL as! URL)
    webview.load(request as URLRequest)
}

it shows this error:

fatal error: unexpectedly found nil while unwrapping an Optional value 2017-02-02 16:43:36.645898 pixel[5112:1996136] fatal error: unexpectedly found nil while unwrapping an Optional value

thanks is advance

回答1:

Try to encode your url and use Swift native type URL and URLRequest instead of NSURL and NSURLRequest.

let stringUrl = "http://url.com/dev2/billboard/geo/\(lat)/\(lng)"
if let encodedURL = stringUrl.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
   let url = URL(string: encodedURL) {
      webview.load(URLRequest(url: url))
}

Edit: I have tried url that you have added in comment it is showing perfectly when you encode it with urlQueryAllowed. May be you have not added NSAppTransportSecurity with your info.plist file try to add once and it will works for you too.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>