How to accomplish a simple web browser using Swift in iOS

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.

Simulator Screen Shot - iPhone 8 - 2018-12-08 at 15.16.07

The codes of WebViewController shows as follows.

import UIKit
import WebKit

class WebViewController: UIViewController, WKUIDelegate {

    var webView: WKWebView!
    var urlString: String!
    override func 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() {
        urlString = ""
        let url = URL(string: urlString)!
        let request = URLRequest(url: url)
        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) {
    @IBAction func backButtonTapped(_ sender: Any) {
    @IBAction func forwardButtonTapped(_ sender: Any) {
    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) { urlString)!)
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent


Thanks to Web View Controller – Design+Code.



Fill in your details below or click an icon to log in: 徽标

You are commenting using your account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理