Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect when user has swiped left or right to go back or forth on WKWebView

I am using a WKWebView and I allowed back and forward navigation gestures :

myWkWebView.allowsBackForwardNavigationGestures = true

Now, the user has two ways to go back : either by pushing a button or by swiping left. The behaviors would be different, so I am wondering how I can know when a user has just swiped left / right so I can handle this.

I looked into WKNavigationDelegate reference ( https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKNavigationDelegate_Ref/ ) but I couldn't find anything useful.

Any idea ?

EDIT

I forgot to say that I also tried to add swipe gesture recognizers, this way :

    let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(MyVC.respondToSwipeLeftOrRight(_:)))
    swipeRight.direction = UISwipeGestureRecognizerDirection.Right
    let swipeLeft = UISwipeGestureRecognizer(target: self, action: #selector(MyVC.respondToSwipeLeftOrRight(_:)))
    swipeLeft.direction = UISwipeGestureRecognizerDirection.Left
    self.view.addGestureRecognizer(swipeRight)
    self.view.addGestureRecognizer(swipeLeft)
    myWkWebView.scrollView.panGestureRecognizer.requireGestureRecognizerToFail(swipeRight)
    myWkWebView.scrollView.panGestureRecognizer.requireGestureRecognizerToFail(swipeLeft)

But they are not triggered everytime I swipe left or right.

like image 915
Randy Avatar asked Oct 19 '22 09:10

Randy


1 Answers

private var currentBackForwardItem: WKBackForwardListItem?
private func handleBackForwardWebView(navigationAction: WKNavigationAction) {
    if navigationAction.navigationType == .BackForward {
        let isBack = webView.backForwardList.backList
            .filter { $0 == currentBackForwardItem }
            .count == 0

        if isBack {

        } else {

        }
    }

    currentBackForwardItem = webView.backForwardList.currentItem
}

func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
    handleBackForwardWebView(navigationAction)
    decisionHandler(.Allow)
}
like image 115
binhapp Avatar answered Dec 12 '22 04:12

binhapp