解包可选值 WKWebView 时意外发现 nil 获取参数 [英] unexpectedly found nil while unwrapping an Optional value WKWebView get parameters

查看:35
本文介绍了解包可选值 WKWebView 时意外发现 nil 获取参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理 WKWebView,当我加载一个没有这样参数的 url 时它工作正常

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)
}

它显示此错误:

致命错误:在展开可选值时意外发现 nil2017-02-02 16:43:36.645898 pixel[5112:1996136] 致命错误:解包可选值时意外发现 nil

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

提前谢谢

推荐答案

尝试编码您的 url 并使用 Swift 原生类型 URLURLRequestcode> 而不是 NSURLNSURLRequest.

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))
}

我已经尝试过您在评论中添加的 url,当您使用 urlQueryAllowed 对其进行编码时,它可以完美显示.可能您还没有在 info.plist 文件中添加 NSAppTransportSecurity 尝试添加一次,它也适用于您.

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>

这篇关于解包可选值 WKWebView 时意外发现 nil 获取参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆