Swift 3使用webview url中pickerview的值

时间:2016-12-20 18:12:18

标签: ios swift

我一直在尝试在我的网页浏览网址

中添加来自pickerview的变量值
 var ["1","2", "3"] 

 func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
            storedName = names[row]
            pickerViewButton.text = storedName

            print("\(Myvar.text)")
            let url = URL (string: "http://examplesite.com/search.php?name=\(myvar.text)")
            let request = URLRequest(url: url as URL!);
            Webview.loadRequest(request as URLRequest);
        }

例如,我的网址最终会像这样#34; http://examplesite.com/search.php?name=1"使用pickerView选择上面数组的第一个值。

但是我一直收到以下致命错误

"致命错误:在打开可选值时意外发现nil"

编辑1:

storedName = names[row]
dropdownButtonLabel.text = storedName

let domainAPI = "http://examplesite.com/search.php?"
let request = URLRequest(url: url);
Webview.loadRequest(request as URLRequest);
let query = "name=\(storedName)"

if let queryPercentEncoded = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: domainAPI + queryPercentEncoded) {
    print(url)
}

这就是我现在所拥有的

1 个答案:

答案 0 :(得分:0)

确保对您的网址查询参数进行百分比编码。你可以这样做:

let domainAPI = "http://examplesite.com/search.php?"
let query = "name=\(storedName)"
if let queryPercentEncoded = query.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
    let url = URL(string: domainAPI + queryPercentEncoded) {
    let request = URLRequest(url: url)
    Webview.loadRequest(request)
}