Updated 20 September 2022
This article is on how to show an Alert view in UIWebView.
The weblinks containing the pop-ups or alerts can be handled in WebKit.
UIWebView delegate functions can handle the alert elegantly in the iOS application.
So let’s start learning.
Integrating Alert View in Weblink
Firstly let’s create a web link that contains an alert view.
Go to our favorite website W3School
It’s time to add the code to display the alert on the website.
Add the below code for displaying the alert view on the website.
Now hit run in the editor, and you will see the webpage with a button named “Show Alert”
Now click on the Show Alert button, and you will see a pop-up on the webpage as below.
Copy the web link, we have to open this inside our UIWebview in Swift.
Now let’s Show an Alert View in UIWebView.
Integrating Alert View in UIWebView
We will open the copied web link on the previous section inside our UIWebView in Swift.
Create an Xcode project and add UIWebView in your ViewController class as below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
import UIKit import WebKit class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate { var wkWebView: WKWebView! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. wkWebView = WKWebView(frame: view.bounds, configuration: WKWebViewConfiguration()) wkWebView.uiDelegate = self wkWebView.navigationDelegate = self view.addSubview(wkWebView!) let url = URL(string: "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_alert")! wkWebView.load(URLRequest(url: url)) } // your copied URL here } |
Now add the WebView function runJavaScriptAlertPanelWithMessage that will actually handle the displaying of the alert in our application.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert) let title = NSLocalizedString("OK", comment: "OK Button") let ok = UIAlertAction(title: title, style: .default) { (action: UIAlertAction) -> Void in alert.dismiss(animated: true, completion: nil) } alert.addAction(ok) present(alert, animated: true) completionHandler() } |
This will pop up an alert view in our application as shown below.
Now you are done integrating the Alert view in UIWebview.
That’s all for this article.
We hope you liked the article.
Please visit my other blogs here.
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.