I have a react-native project and decided to move away from it and go native but want to salvage the Javascript code. I ended up using webviews and make native calls from the WebView based on what native capability we needed for Android and iOS. I was able to do with Android via javascriptInterface
. I am now struggling to do it for iOS. I made a test using Swift and WKWebView
.
Here is what I've come up with so far:
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0;" />
<title>JavaScript Interface</title>
</head>
<script type="text/javascript">
function takePicture() {
window.webkit.messageHandlers.native.postMessage();
}
</script>
<body style="background-color: RebeccaPurple">
<h1>This is HTML</h1>
<p>
<input type="button" value="HTML button" onClick="takePicture()"/>
</p>
</body>
</html>
ViewController.swift
import UIKit
import WebKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let webView = WKWebView(frame: view.frame)
view.addSubview(webView)
let url = Bundle.main.url(forResource: "index", withExtension: "html", subdirectory: "/")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
let config = WKWebViewConfiguration()
let userContentController = WKUserContentController()
userContentController.add(self, name: "native")
config.userContentController = userContentController
}
func takePhoto() {
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerController.SourceType.camera) {
let imagePicker = UIImagePickerController()
imagePicker.delegate = self
imagePicker.sourceType = UIImagePickerController.SourceType.camera
imagePicker.allowsEditing = false
self.present(imagePicker, animated: true, completion: nil)
}
}
}
extension ViewController: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "native" {
takePhoto()
}
}
}