I am trying to make a call from a javascript function in a UIWebView to Swift in iOS 10. I have setup a very basic project just to try and get this working, the code is below.
import UIKit
class ViewController: UIViewController, UIWebViewDelegate {
@IBOutlet var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let url = Bundle.main.url(forResource: "products", withExtension: "html")
let request = NSURLRequest(url: url! as URL)
webView.loadRequest(request as URLRequest)
}
@IBAction func closeDocumentViewer() {
displayView.isHidden = true;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
If I just one to receive a string from a javascript function what would I have to add to the above?
You must a custom URL Scheme
such as myawesomeapp
and intercept requests to it using:
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
Fire a call to native code using window.location=myawesomeapp://hello=world
, and get the query params you pass from request.URL.query
in the native code.
For more information, see my question about UIWebView
s here: JavaScript synchronous native communication to WKWebView