Apple provides us the WebKit framework to display web content in windows. Here is a simple example to accomplish a simple web browser depending on the WebKit.
The basic theory is to state an object of WKWebView which will hold all operators, for example back/forward/refresh. In this example, I make a WebViewController to do all things, in which there're some Bar Button Item
to do different operators in Navigation Bar
and Toolbar
, just as the following screenshot shows.

The codes of WebViewController shows as follows.
import UIKit
import WebKit
class WebViewController: UIViewController, WKUIDelegate {
var webView: WKWebView!
var urlString: String!
override func loadView() {
super.loadView()
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
deinit {
webView.removeObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress))
}
override func viewDidLoad() {
super.viewDidLoad()
urlString = "https://wangmingjun.com"
let url = URL(string: urlString)!
let request = URLRequest(url: url)
webView.load(request)
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.estimatedProgress), options: .new, context: nil)
}
@IBAction func doneButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
@IBAction func refreshButtonTapped(_ sender: Any) {
webView.reload()
}
@IBAction func backButtonTapped(_ sender: Any) {
webView.goBack()
}
@IBAction func forwardButtonTapped(_ sender: Any) {
webView.goForward()
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "estimatedProgress" {
if webView.estimatedProgress == 1.0 {
title = webView.title
}
}
}
@IBAction func actionButtonTapped(_ sender: Any) {
let activityItems = [urlString] as! [String]
let activityController = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)
activityController.excludedActivityTypes = [UIActivity.ActivityType.postToFacebook]//, UIActivityType.markupAsPDF]
present(activityController, animated: true, completion: nil)
}
@IBAction func safariButtonTapped(_ sender: Any) {
UIApplication.shared.open(URL(string: urlString)!)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
}
Thanks to Web View Controller – Design+Code.
分类:iOS