Step1 :
Make use of WKWebView rather than UIWebView in your ViewController.
Step2 :
Make your ViewController be the delegate of WKWebView
webView.navigationDelegate = self
webView.uiDelegate = self
Step3 :
Finally implement WKNavigationDelegate in your ViewController
extension ViewController : WKNavigationDelegate{
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
//now u and ur server team can decide on what url will they redirect and what will be url string on login success
//lets say u and ur server team decides url to be https://some_base_url/login/success
if url.absoluteString.contains("/login/success") {
// this means login successful
decisionHandler(.cancel)
_ = self.navigationController?.popViewController(animated: false)
}
else {
decisionHandler(.allow)
}
}
}
EDIT:
As OP has issue with his code am updating answer to solve the issue
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate{
var webView: WKWebView!
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.uiDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
let myURL = URL(string: "https://")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
func webView(
_ webView: WKWebView,
decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
guard let url = navigationAction.request.url else {
decisionHandler(.allow)
return
}
if url.absoluteString.contains("/login/success") {
// this means login successful
decisionHandler(.cancel)
_ = self.navigationController?.popViewController(animated: false)
}
else {
decisionHandler(.allow)
}
}
}