2016-12-13 23 views
-1

我傳遞一個字符串變量來打開一個網址在網絡視圖中,當我創建基於字符串的URL不解開。我不確定我做錯了什麼。以下是代碼:Swift 3可選的麻煩。無法打開URL傳遞字符串

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


} 
+0

你能告訴你的'theUrlString'的內容是什麼? –

+1

你有沒有嘗試把代碼放在'viewWillAppear'方法中?也看看這裏http://stackoverflow.com/a/33607311/5327882 – ronatory

+1

@ronatory很好的建議。它有可能將視圖加載到內存中,將'theUrlString'實例變量設置爲一個空的String值。根據您的應用程序的佈局,可能不會再調用'viewDidLoad()'方法。 –

回答

1

您的theUrlString未正確編碼。因此,當您使用URL(string:)時,它將返回nil(表示傳入的URL字符串格式錯誤)。

我會推薦使用URLComponents來創建您的網址。

喜歡的東西:

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

+0

就是這樣。謝謝! – Rmyers