In iOS, how can I call an Objective-C method from Javascript in a UIWebView
and have it send data back to the Javascript? I know that this could be done on OS X using the Webkit library, but is this possible on iOS? How does PhoneGap achieve this?
相关问题
- CALayer - backgroundColor flipped?
- Core Data lightweight migration crashes after App
- How can I implement password recovery in an iPhone
- State preservation and restoration strategies with
- “Zero out” sensitive String data in Swift
相关文章
- 现在使用swift开发ios应用好还是swift?
- How to properly initialize an ErrorEvent in javasc
- UITableView dragging distance with UIRefreshContro
- TCC __TCCAccessRequest_block_invoke
- Where does a host app handle NSExtensionContext#co
- xcode 4 garbage collection removed?
- Unable to process app at this time due to a genera
- Swift - hide pickerView after value selected
Changing page's location can cause several issues:
The solution, as offered here, is:
Keep using the same URL technique (on js and objective-c), just change the location with an iframe:
Hope that helps
There is an API to call JavaScript directly from Objective-C, but you cannot call Objective-C directly from Javascript.
How to tell your Objective-C code to do something from the Javascript in your WebView
You have to serialize your Javascript action into a special URL and intercept that URL in the UIWebView's delegate's
shouldStartLoadWithRequest
method.There you can deserialize that special URL and interpret it to do what you want on the Objective-C side. (You should return
NO
in the aboveshouldStartLoadWithRequest
method so the UIWebView doesn't use your bogus URL to actually make an HTTP request to load a webpage.)How to Run Javascript Code from Objective-C
Then you can run Javascript from Objective-C by calling this method on your webview.
Example Code
I recommend using a bogus URL scheme so it will be easy to tell the difference between your action URLs and legit requests. You can make this request in the Javascript along these lines:
Then in the
UIWebView.delegate
'sshouldStartLoadWithRequest
method, you can inspect the URL scheme and fragment to check if it's a normal request or one of your special actions. (The fragment of a URL is what comes after the#
.)(Read this answer if you need help deserializing your json string into an NSDictionary.)
From Objective-C: You can pass a javascript function in a string to UIWebView. The web page will execute it and return a result. This way you can pass variables and get data back from Javascript.
Example:
From Javascript: Pass your data inside the URL. Intercept URL requests in UIWebViewDelegate. Get the data and abort URL request by returning NO.
Intercept the URL request