Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lapinek/02882b18e234bf79ce4a51788b23b9a4 to your computer and use it in GitHub Desktop.
Save lapinek/02882b18e234bf79ce4a51788b23b9a4 to your computer and use it in GitHub Desktop.
// ViewController.swift
// . . .
// MARK: Conforming to WKScriptMessageHandler protocol
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(#function)
if message.name == "callback", let messageBody = message.body as? String, let messageBodyData = messageBody.data(using: .utf8) {
let decoder = JSONDecoder()
var messageBodyJson: AuthenticationResponse?
do {
messageBodyJson = try decoder.decode(AuthenticationResponse.self, from: messageBodyData)
messageBodyJson?.callbacks.forEach {
callback in
if callback.type == "code" {
/**
Example action against the web content.
*/
let scriptSource = "document.body.style.backgroundColor = 'lightgreen'"
// Example action performed in the native app.
let webView = self.view.viewWithTag(webViewTag) as? WKWebView
let alert = UIAlertController(title: "Native Prompt", message: "Enter the code. \nThe correct one is: 0000", preferredStyle: UIAlertController.Style.alert)
alert.addTextField() {
textField in
alert.addAction(
UIAlertAction(title: NSLocalizedString("Cancel", comment: "Cancel Action"), style: UIAlertAction.Style.cancel) {
(_: UIAlertAction) in
webView?.removeFromSuperview()
}
)
alert.addAction(
UIAlertAction(title: NSLocalizedString("Submit", comment: "Submit Action"), style: UIAlertAction.Style.default) {
(_: UIAlertAction) in
let newValue = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
if (newValue != "0000") {
webView?.removeFromSuperview()
} else {
// Performing the action against the web content.
webView?.evaluateJavaScript(scriptSource, completionHandler: nil)
}
}
)
}
present(alert, animated: false)
}
}
} catch {
print("Error decoding callback message: ", error.localizedDescription)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment