Swipe gesture for back/forward in UIWebView?

Accepted answer in Swift 3:

override func viewDidLoad() {
    super.viewDidLoad()

    let swipeLeftRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
    let swipeRightRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(handleSwipe(recognizer:)))
    swipeLeftRecognizer.direction = .left
    swipeRightRecognizer.direction = .right

    webView.addGestureRecognizer(swipeLeftRecognizer)
    webView.addGestureRecognizer(swipeRightRecognizer)
}

@objc private func handleSwipe(recognizer: UISwipeGestureRecognizer) {
    if (recognizer.direction == .left) {
        if webView.canGoForward {
            webView.goForward()
        }
    }

    if (recognizer.direction == .right) {
        if webView.canGoBack {
            webView.goBack()
        }
    }
}

Answer in Swift 3 & Swift 4

If anyone is still having problems. This worked for me:

Find "didFinish" add / replace the following code.

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    self.didFinish()

    webView.allowsBackForwardNavigationGestures = true

}

The main code you need is just one line. It comes after self.didFinish() but still within the {} brackets.

webView.allowsBackForwardNavigationGestures = true


Why not just use a swipe gesture recognizer?

UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];
UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipe:)];

// Setting the swipe direction.
[swipeLeft setDirection:UISwipeGestureRecognizerDirectionLeft];
[swipeRight setDirection:UISwipeGestureRecognizerDirectionRight];

// Adding the swipe gesture on WebView
[webView addGestureRecognizer:swipeLeft];
[webView addGestureRecognizer:swipeRight];

- (void)handleSwipe:(UISwipeGestureRecognizer *)swipe {

if (swipe.direction == UISwipeGestureRecognizerDirectionLeft) {
    NSLog(@"Left Swipe");
}

if (swipe.direction == UISwipeGestureRecognizerDirectionRight) {
    NSLog(@"Right Swipe");   
} 

}