I am not specialist in WebKit Framework :) cannot really recall how i came up with this solution now in details however webview.isLoading
checks whether the view is loading new content or not. So if it is not loading we can present alert to a user.
Your code actually works but there is a caveat. apple.com
has regional settings/or other settings or whatever it is called so when you type in in the search bar of the browser apple.com it might redirect you to your region or make other actions behind the scenes that is why you have your alert triggered for that particular site but not for hackingwithswift.com. Should you put any other site that doesn't do the same as apple.com it will work fine.
Using webview.isLoading
we can check if loading is happening at all, and if it is not we trigger alert, so kind of avoding this behavior.
Hope that helps :)
PS. With this modification it won't crash your code. As in your code if you replace apple.com with yahoo.com it just crashes.
if let host = url?.host {
for website in websites {
if host.contains(website) {
decisionHandler(.allow)
return
}
}
} else {
let ac = UIAlertController(title: "Blocked", message: "You are not allowed", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "Continue", style: .default, handler: nil))
present(ac, animated: true)
}
decisionHandler(.cancel)
with yahoo.com
is the same thing as with apple.com
. However google.com
is working fine. Also that will not trigger an alert if you try to navigate from within allowed sites to another site, but view.Loading you can handle this.