Swift 3 可选的麻烦.无法使用传入的字符串解开 url [英] Swift 3 Optional trouble. Can't unwrap url with passed in string
本文介绍了Swift 3 可选的麻烦.无法使用传入的字符串解开 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在传入一个字符串变量以在 web 视图中打开一个 url,当我根据该字符串创建 url 时,它没有展开.我不确定我做错了什么.代码如下:
I am passing in a string variable to open a url in a webview and when I create the url based on the string its not unwrapping. I'm not sure what I'm doing wrong. Here is the code:
class WebViewController: UIViewController, WKUIDelegate {
var urlString:String?
var vehicle:Vehicle?
var theUrlString = "http://www.ksl.com/auto/search/" //This variable is set in the prepareForSegue in a previous view controller. It is set correctly
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
if let urlStri = urlString {
print("url is " + urlStri)
theUrlString = urlStri
}else {
}
}
override func viewDidLoad() {
super.viewDidLoad()
print("theUrlString is " + theUrlString) // this correctly prints: theUrlString is http://www.ksl.com/auto/search/index?keyword=&make%5B%5D=Chevrolet&model%5B%5D=Silverado 1500&yearFrom=2006&yearTo=2008&mileageFrom=&mileageTo=&priceFrom=&priceTo=&zip=&miles=25&newUsed%5B%5D=All&sellerType%5B%5D=&postedTime%5B%5D=&titleType%5B%5D=&body%5B%5D=&transmission%5B%5D=&cylinders%5B%5D=&liters%5B%5D=&fuel%5B%5D=&drive%5B%5D=&numberDoors%5B%5D=&exteriorCondition%5B%5D=&interiorCondition%5B%5D=&cx_navSource=hp_search
if let url = URL(string: theUrlString){
let myRequest = URLRequest(url: url) //In debugging, it never makes it inside the if statement here
webView.load(myRequest)
}
}
推荐答案
您的 theUrlString
未正确编码.因此,当您使用 URL(string:)
时,它返回 nil
(表明传入的 URL 字符串格式错误).
Your theUrlString
is not properly encoded. As a result, when you use URL(string:)
, it is returning nil
(an indication that the URL string passed in was malformed).
我建议使用 URLComponents
来创建您的 URL.
I would recommend using URLComponents
to create your URL.
类似于:
var urlComponents = URLComponents(string: "http://www.ksl.com/auto/search/index")
var arguments: [String: String] = [
"keyword": "",
"make": "Chevrolet",
"model": "Silverado 1500"
]
var queryItems = [URLQueryItem]()
for (key, value) in arguments {
queryItems.append(URLQueryItem(name: key, value: value))
}
urlComponents?.queryItems = queryItems
if let url = urlComponents?.url {
print(url) // http://www.ksl.com/auto/search/index?keyword=&model=Silverado%201500&make=Chevrolet
}
URLComponents
API 参考:https://developer.apple.com/reference/foundation/urlcomponents
这篇关于Swift 3 可选的麻烦.无法使用传入的字符串解开 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文