Analyzing your code I found that:
- No communication between client (web page) and container (iOS).
- The Uiwebview component was depreciated consequently, use the Wkwebview.
Thus, to display the alert correctly, your code should have a structure close to the example 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 above code, run the javascript command on the console or directly on some site function:
window.webkit.messageHandlers.alerta.postMessage("texto de parametro");
Evidence of testing:
Don’t forget to add the information NSAppTransportSecurity
in your plist file, otherwise your site might not be loaded.
Hello Adriano can put your code so we can help you?
– Maurício Z.B
Can someone help me? =(
– Adriano Rios
Somebody give me a light? :'(
– Adriano Rios