How to call Objective-C from Javascript?

前端 未结 8 1709
误落风尘
误落风尘 2020-11-22 17:38

I have a WebView, and I want to call a view in Objective-C from JavaScript. Does someone know how I can do this?


I have this code in my ViewController:

8条回答
  •  猫巷女王i
    2020-11-22 18:05

    The standard workaround for UIWebView is to set a UIWebViewDelegate, and implement the method webView:shouldStartLoadWithRequest:navigationType:. In your JavaScript code, navigate to some fake URL that encodes the information you want to pass to your app, like, say:

    window.location = "fake://myApp/something_happened:param1:param2:param3";
    

    In your delegate method, look for these fake URLs, extract the information you need, take whatever action is appropriate, and return NO to cancel the navigation. It's probably best if you defer any lengthy processing using some flavor of performSelector.

提交回复
热议问题