Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS - How to create WKWebView Back Button programmatically?

I am attempting to create a back button for my iOS WKWebView app so that way when the user clicks on the button it takes them to the previous WKWebView page. I have found numerous tutorials on how to do this with IB but not with straight code. This is what I have so far:

Original ViewController.swift:

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    private var webView: WKWebView!

    let wv = WKWebView(frame: UIScreen.mainScreen().bounds) //needed for working webview

    self.webView = WKWebView(frame: frame)
    self.webView.navigationDelegate = self

    func rightbutton(text: String, action: Selector) {
        let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
        self.navigationItem.rightBarButtonItem = rightButton
    }

    func action() {
        if self.webView.canGoBack {
            print ("Can go back")
            self.webView.goBack()
            self.webView.reload()

        } else {
            print ( "Can't go back")
        }
    }


    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url =  NSURL(string: "http://communionchapelefca.org/app-home") else { return }
        wv.navigationDelegate = self
        wv.loadRequest(NSURLRequest(URL: url))
        view.addSubview(wv)


        webView.goBack()
        webView.reload()



        prefButton()
        //backButton()

        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionEnter",
            object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionUpdate",
            object: nil)

        NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionExit",
            object: nil)

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func prefButton () {
        let image = UIImage(named: "icon-pref128") as UIImage?
        let button   = UIButton(type: UIButtonType.Custom) as UIButton
        let screenSize: CGRect = UIScreen.mainScreen().bounds
        let screenWidth = screenSize.width
        let screenHeight = screenSize.height

        button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
        button.setImage(image, forState: .Normal)
        button.addTarget(self, action: "buttonClicked:", forControlEvents:.TouchUpInside)
        self.view.addSubview(button)
    }

    func buttonClicked(sender:UIButton)
    {
        UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
    }

    func receiveNotification(notification: NSNotification) {
        print(notification.userInfo)
    }

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .LinkActivated  {
            if let newURL = navigationAction.request.URL,
                host = newURL.host where !host.containsString("communionchapelefca.org") &&
                    UIApplication.sharedApplication().canOpenURL(newURL) {
                        if UIApplication.sharedApplication().openURL(newURL) {
                            print(newURL)
                            print("Redirected to browser. No need to open it locally")
                            decisionHandler(.Cancel)
                        } else {
                            print("browser can not url. allow it to open locally")
                            decisionHandler(.Allow)
                        }
            } else {
                print("Open it locally")
                decisionHandler(.Allow)
            }
        } else {
            print("not a user click")
            decisionHandler(.Allow)
        }
    }

}

Any suggestions? Thanks in advance.

EDIT: attached entire ViewController rather than snippet of code.

EDIT2: Answer by k8mil was close as his answer didnt load the initial URL. Below is the only adjustment from his answer:

private func createWebView() {
        guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else { return }
        let frame  = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
        self.webView = WKWebView(frame: frame)
        self.webView.navigationDelegate = self
        self.webView.loadRequest(NSURLRequest(URL: url))
        self.view.addSubview(self.webView)
    }
like image 700
Greg Williams Avatar asked Apr 07 '16 20:04

Greg Williams


People also ask

How do I go back to WKWebView?

One of the many advantages of WKWebView over UIWebView is its ability to draw on some of the native user interface of Safari. It's a long way from the SFSafariViewController that was introduced in iOS 9.0, but you can enable the built-in gestures that let users go back and forward by swiping left and right.

How do I add WKWebView to my storyboard?

First add the web view as a UIWebView outlet in the storyboard / IB. This will give you a property like this: @property (weak, nonatomic) IBOutlet UIWebView *webView; Then just edit your code to change it to a WKWebView.

How do I import WKWebView into Objective C?

You can implement WKWebView in Objective-C, here is simple example to initiate a WKWebView : WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init]; WKWebView *webView = [[WKWebView alloc] initWithFrame:self. view. frame configuration:theConfiguration]; webView.


1 Answers

Try to call webView.goBack() method on your WKWebView instance instead WKWebView.goBack(). Also after goBack() you can call a webView.reload() method to make sure you're on the correct page.

I edited your code a bit

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

private var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    guard let url = NSURL(string: "http://communionchapelefca.org/app-home") else {
        return
    }

    //create WebView and Back button
    createWebView()
    backButton()


    prefButton()


    NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionEnter",
            object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionUpdate",
            object: nil)

    NSNotificationCenter.defaultCenter().addObserver(self,
            selector: "receiveNotification:",
            name: "BeaconServiceRegionExit",
            object: nil)

}


private func createWebView() {
    let frame  = UIScreen.mainScreen().bounds // or different frame created using CGRectMake(x,y,width,height)
    self.webView = WKWebView(frame: frame)
    self.webView.navigationDelegate = self
    self.view.addSubview(self.webView)
}

func addBackButton(text: String, action: Selector) {
    //this function will add Button on your navigation bar e

    let rightButton = UIBarButtonItem(title: text, style: .Plain, target: self, action: action)
    self.navigationItem.rightBarButtonItem = rightButton
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func prefButton() {
    let image = UIImage(named: "icon-pref128") as UIImage?
    let button = UIButton(type: UIButtonType.Custom) as UIButton
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
    button.setImage(image, forState: .Normal)
    button.addTarget(self, action: "buttonClicked:", forControlEvents: .TouchUpInside)
    self.view.addSubview(button)
}

func backButton() {
    let image = UIImage(named: "icon-back") as UIImage?
    let button = UIButton(type: UIButtonType.Custom) as UIButton
    let screenSize: CGRect = UIScreen.mainScreen().bounds
    let screenWidth = screenSize.width
    let screenHeight = screenSize.height

    button.frame = CGRectMake(screenWidth * 0.85, screenHeight * 0.90, 56, 56) // (X, Y, Height, Width)
    button.setImage(image, forState: .Normal)
    button.addTarget(self, action: "customGoBack:", forControlEvents: .TouchUpInside)
    self.view.addSubview(button)
}

func customGoBack(sender: UIButton) {
    if self.webView.canGoBack {
        print("Can go back")
        self.webView.goBack()
        self.webView.reload()
    } else {
        print("Can't go back")
    }
}

func buttonClicked(sender: UIButton) {
    UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
}

func receiveNotification(notification: NSNotification) {
    print(notification.userInfo)
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    if navigationAction.navigationType == .LinkActivated {
        if let newURL = navigationAction.request.URL,
        host = newURL.host where !host.containsString("communionchapelefca.org") &&
                UIApplication.sharedApplication().canOpenURL(newURL) {
            if UIApplication.sharedApplication().openURL(newURL) {
                print(newURL)
                print("Redirected to browser. No need to open it locally")
                decisionHandler(.Cancel)
            } else {
                print("browser can not url. allow it to open locally")
                decisionHandler(.Allow)
            }
        } else {
            print("Open it locally")
            decisionHandler(.Allow)
        }
    } else {
        print("not a user click")
        decisionHandler(.Allow)
    }
}

}

Also you don't neeed another instance of WKWebView because you have declared previously in :

private var webView : WKWebView!

so it is not necessary :

wv.navigationDelegate = self
wv.loadRequest(NSURLRequest(URL: url))  
view.addSubview(wv)

For me it works.

Hope this will help you :)

like image 150
kamwysoc Avatar answered Sep 27 '22 22:09

kamwysoc