0

I have an app that displays a webView of a web page. The web consists of a main page with a lot of subpages. When I am on the main page I want the navigation Back button to to keep the default behaviour of going back to the previous view controller. But when the web is on a subpage I would like the navigation Back button to take the web to the main web page.

So I need to catch when the user presses the back button and if he is on a web subpage take him to the web main page and prevent the webView from closing. I was thinking that I can catch the back button using viewWillDisappear(), but how can I prevent the view from closing?

  • Do you need to know how to do test for the webview components, or do you just need to know how you would set it up structure-wise with the back button? – Benjamin Lowry Apr 24 '16 at 09:35

2 Answers2

0

Check this post out:

Execute action when back bar button of UINavigationController is pressed

Something like this ought to do, in your view controller code:

override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
    let customBackButtonItem = UIBarButtonItem(title: "Back", style: .Bordered, target: self, action:#selector(customBackMethod(_:)))
    self.navigationItem.leftBarButtonItem = customBackButtonItem
}

// @objc is so we can use #selector() up above
@objc func customBackMethod(sender: UIBarButtonItem) {
    if webView.canGoBack {
        webView.goBack()
    }
}

Note that you may have to use UIBarButtonItem(image:, style:, target:, action:) if you want a 'back' image, or UIBarButtonItem(customView:). See this question and answer for more details: https://stackoverflow.com/a/36180934/892990

Community
  • 1
  • 1
jperl
  • 1,066
  • 7
  • 14
0

Similar to KickimusButticus' answer:

If you want to more easily do it using the storyboard and such, you could hook up your back button to an IBAction like so:

@IBAction func back() {

}

And have internal testing for whether or not the user is in a sub-page of the webview. If they are, you can mess with the webview. If they are on the home page, you could simply use the back button to segue to your main view controller or use the self.dismissViewControllerAnimated(true, completion: nil) to dismiss that view controller.

Benjamin Lowry
  • 3,730
  • 1
  • 23
  • 27
  • I implemented KickimusButticus suggestion and it works. I do however think this looks more elegant, so I tried it, but my back() function never get called. I think I have connected it correct it looks so with the little circle with the back dot in it. Any suggestion to what I might be doing wrong? – Gongevangen Apr 25 '16 at 20:12
  • @Gongevangen if you connected it properly, then it should be called whenever you click on the back button. I would suggest you check that you have the right connection by looking at the connection in the attributes inspector. Perhaps try reconnecting it and see if that works. – Benjamin Lowry Apr 25 '16 at 22:03