Looking at your code, I found that:
- There is no communication between the client (web page) and the container (iOS).
- The UIWebView component has been deprecated accordingly, use the WKWebView .
In order to display the alert correctly, your code should have a structure similar to the one below:
import UIKit
import WebKit
class ViewController: UIViewController, WKUIDelegate, WKScriptMessageHandler {
// Troquei de UIWebView para WKWebView
var webView: WKWebView!
override func viewDidLoad() {
webView = WKWebView(frame: UIScreen.main.bounds)
webView.configuration.userContentController.add(self, name: "alerta") //window.webkit.messageHandlers.alerta.postMessage("trigger from JS");
webView.uiDelegate = self
self.view.addSubview(webView)
if let url = URL(string: "http://office.unick.forex/login.php")
{
let request = URLRequest(url: url)
webView.load(request)
}
}
func alertaGenerico() {
let alertController = GlobalAlertController(title: "", message: "Você tem certeza?", preferredStyle: .alert)
let cancelar = UIAlertAction(title: "Cancelar", style: .default, handler: nil)
alertController.addAction(cancelar)
let ok = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(ok)
alertController.show()
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "alerta" {
print(message.body)
alertaGenerico()
}
}
}
//--------
// MARK: - Exibição global na UIViewController
//--------
protocol GlobalWindow {
func show(animated flag: Bool, completion: (() -> Void)? )
}
extension GlobalWindow where Self : UIViewController {
func show(animated flag: Bool = true, completion: (() -> Void)? = nil) {
if let window = UIApplication.shared.keyWindow?.rootViewController {
window.present(self, animated: flag, completion: completion)
}
}
}
class GlobalAlertController : UIAlertController, GlobalWindow {}
To test the code above, run the javascript command on the console or directly on some site function:
window.webkit.messageHandlers.alerta.postMessage("texto de parametro");
Evidence of testing:
Do not forget to add the NSAppTransportSecurity
information to your plist file, otherwise your site may not load.