WKWebView加載頁面
import UIKit
import WebKit
class ViewController: UIViewController{
var webView : WKWebView!
var loadType : UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
loadType = UISegmentedControl(items: ["顯示網站","顯示HTML","顯示本地文件","loadData顯示本地"])
loadType.frame = CGRect(x: 0, y: 0, width: self.view.bounds.size.width, height: 40)
loadType.selectedSegmentIndex = 1
loadType.addTarget(self, action: #selector(ViewController.typeChanged(_:)), for: .valueChanged)
webView = WKWebView(frame: CGRect(x: 0, y: 40, width: self.view.bounds.size.width, height: self.view.bounds.size.height - 40))
typeChanged(loadType)
self.view.addSubview(webView)
self.view.addSubview(loadType)
}
@objc func typeChanged(_ sender:UISegmentedControl){
let index = sender.selectedSegmentIndex
switch index {
case 0:
//設置訪問的url
let url = URL(string: "https://www.jianshu.com/u/5ab366f0368f")
//根據url建立請求
let urlRequest = URLRequest(url: url!)
//加載請求
webView.load(urlRequest)
case 1:
let html = "<h1>歡迎來到:<a href='https://www.jianshu.com/u/5ab366f0368f'>Swift學習</a></h1>"
webView.loadHTMLString(html, baseURL: nil)
case 2:
let path = Bundle.main.path(forResource: "File", ofType: "pdf")
let url = URL(fileURLWithPath: path!)
let urlRequest = URLRequest(url: url)
webView.load(urlRequest)
case 3:
let path = Bundle.main.path(forResource: "File", ofType: "pdf")
let url = URL(fileURLWithPath: path!)
let data = try! Data(contentsOf: url)
webView.load(data, mimeType: "application/pdf", characterEncodingName: "utf-8", baseURL: NSURL() as URL)
default:
print("出現錯誤")
}
}
}