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)
}
}
Your
theUrlString
is not properly encoded. As a result, when you useURL(string:)
, it is returningnil
(an indication that the URL string passed in was malformed).I would recommend using
URLComponents
to create your URL.Something like:
URLComponents
API Reference: https://developer.apple.com/reference/foundation/urlcomponents