2016-12-13 3 views
-1

私は文字列変数を渡してWebビューでURLを開き、その文字列に基づいてURLをアンラッピングしないで作成します。私は何が間違っているのか分かりません。コードは次のとおりです。スイフト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

@notary良い提案。 'theUrlString'インスタンス変数を空のString値に設定して、ビューがメモリにロードされた可能性があります。あなたのアプリケーションのレイアウトによっては、 'viewDidLoad()'メソッドは再び呼び出されないかもしれません。 –

答えて

1

theUrlStringが正しくエンコードされていません。その結果、URL(string:)を使用すると、nil(渡されたURL文字列が不正であることを示す)が返されます。

URLComponentsを使用して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

+0

それでした。ありがとう! – Rmyers

関連する問題