Description:
App中有時如果需要載入一些外部網站時,可以使用 WKWebView。
這demo是透過webview將google search載入,並搭配search bar來搜尋結果。
Component:
Highlight function:
let urlString: String = "https://www.google.com.tw/"
let url: URL = URL(string: urlString)!
let urlRequest: URLRequest = URLRequest(url: url)
webView.load(urlRequest)
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
searchBar.resignFirstResponder()
var text = searchBar.text
text = text!.replacingOccurrences(of: " ", with: "+") //replace space with a plus sign
let url: URL = URL(string: "https://www.google.com.tw/search?q=\(text!)")!
let urlRequest: URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
Additional:
在iOS 9 之後,應用程式內的 UIWebView 預設為只能載入"https" 的網頁,如果是普通 http 的網頁會無法開啟,若是要開啟"http"網頁則需先設定info.plist,方法如下:
Reference:
Source code on Github