Skip to content

Instantly share code, notes, and snippets.

@developer-shubham101
Last active February 24, 2022 17:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save developer-shubham101/269eff00f78e71697c8ba1305673c87a to your computer and use it in GitHub Desktop.
Save developer-shubham101/269eff00f78e71697c8ba1305673c87a to your computer and use it in GitHub Desktop.
Perform native operation by javascript
//
// WebViewScriptViewController.swift
// UpgradeMySelf-ios
//
// Created by Shubham Sharma on 20/01/20.
// Copyright © 2020 Shubham Sharma. All rights reserved.
//
import UIKit
import WebKit
/// -Html code:
/// -Message need to send
/// var message = {"Status": "SUCCESS", "transactionId": "#PAY123133" };
/// -send messge to webview
/// window.webkit.messageHandlers.paymentResponse.postMessage(message)
let htmlData = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Web View Script</title>
</head>
<body>
<button id="success">Success</button>
<button id="failed">Failed</button>
<button id="sample">Sample</button>
<script>
var success = document.getElementById('success');
var failed = document.getElementById('failed');
var sample = document.getElementById('sample');
success.addEventListener('click', function () {
var message = {
"Status": "SUCCESS",
"transactionId": "#PAY123133"
};
window.webkit.messageHandlers.paymentResponse.postMessage(message)
});
failed.addEventListener('click', function () {
var message = {
"Status": "FAILED",
"transactionId": "#PAY123133"
};
window.webkit.messageHandlers.paymentResponse.postMessage(message)
});
sample.addEventListener('click', function () {
var message = {
"Status": "FAILED",
"transactionId": "#PAY123133"
};
window.webkit.messageHandlers.sample.postMessage(message)
});
</script>
</body>
</html>
"""
class WebViewScriptViewController: UIViewController, WKNavigationDelegate {
@IBOutlet weak var webView: WKWebView!
private var webViewContentIsLoaded = false
override func viewDidLoad() {
super.viewDidLoad()
///register function name like paymentResponse or sample
webView.configuration.userContentController.add(self, name: "paymentResponse")
webView.configuration.userContentController.add(self, name: "sample")
webView.scrollView.bounces = false
webView.navigationDelegate = self
if !webViewContentIsLoaded {
if let url = Bundle.main.url(forResource: "index", withExtension: "html") { ///load html from local
let request = URLRequest(url: url)
webView.load(request)
} else {
webView.loadHTMLString(htmlData, baseURL: nil)
}
webViewContentIsLoaded = true
}
}
func showAlertWithMessage(title: String, message:String ) {
let alert = UIAlertController.init(title: title , message:message , preferredStyle:.alert)
let action = UIAlertAction.init(title: "OK", style: .cancel) { (action) in
}
alert.addAction(action)
self.present(alert, animated:true, completion: nil)
}
}
extension WebViewScriptViewController: WKScriptMessageHandler {
// MARK: - WKScriptMessageHandler
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
print(message.body)
guard let body = message.body as? [String: Any] else {
print("could not convert message body to dictionary: \(message.body)")
showAlertWithMessage(title: "Payment Declined", message: "" )
return
}
guard let status = body["Status"] as? String else {
print("could not convert Status to string: \(body)")
showAlertWithMessage(title: "Payment Declined", message: "" )
return
}
switch status {
case "FAILED":
showAlertWithMessage(title: "Payment Declined", message: "")
print("Transaction Failed")
break
case "SUCCESS":
guard let transactionId = body["transactionId"] as? String else {
print("could not transactionId to string: \(body)")
return
}
print("outerHTML is \(transactionId)")
showAlertWithMessage(title: "Payment Success", message: "Transaction Id \(transactionId)" )
break
default:
print("unknown message type \(status)")
return
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment