JS and iOS communication, the main use of two methods: (PhoneGap framework is based on this principle)
1, the Stringbyevaluatingjavascriptfromstring method of UIWebView
2, the Uiwebviewdelegate
-(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype :(Uiwebviewnavigationtype) Navigationtype method
Example:
The upper part is a UIWebView that implements Uiwebviewdelegate
- -(void) viewdidload
- {
- [Super Viewdidload];
- NSString *path = [[NSBundle mainbundle] pathforresource:@ "Jm/info" oftype:@ "html"];
- Nsurlrequest *request = [nsurlrequest requestwithurl:[nsurl Fileurlwithpath:path];
- [Self.webview Loadrequest:request];
- }
- #pragma mark-uiwebviewdelegate
- -(BOOL) WebView: (UIWebView *) WebView shouldstartloadwithrequest: (nsurlrequest *) Request Navigationtype: ( Uiwebviewnavigationtype) Navigationtype
- {
- if ([Request.mainDocumentURL.relativePath isequaltostring:@ "/getinfo/name"])
- {
- NSString *info = [[Uidevice currentdevice] name];
- NSString *js = [NSString stringwithformat:@ "Showinfo (\" name\ ", \"%@\ ")", info ";
- [Self.webview Stringbyevaluatingjavascriptfromstring:js];
- return false;
- }
- if ([Request.mainDocumentURL.relativePath isequaltostring:@ "/getinfo/systemversion"])
- {
- NSString *info = [[Uidevice currentdevice] systemversion];
- NSString *js = [NSString stringwithformat:@ "Showinfo (\" systemversion\ ", \"%@\ ")", info ";
- [Self.webview Stringbyevaluatingjavascriptfromstring:js];
- return false;
- }
- return true;
- }
JS Code:
- <! DOCTYPE HTML>
- <html>
- <head>
- <title>city</title>
- <Meta charset="Utf-8">
- <Meta name="viewport" content="width=device-width, initial-scale=1">
- <link rel= "stylesheet" href="jquery.mobile-1.0.css"/>
- <script type="Text/javascript" src="Jquery.js"></script>
- <script type="Text/javascript" src="Jquery.mobile-1.0.js"></ Script>
- <script>
- function GetInfo (name)
- {
- window.location = "/getinfo/" +name;
- }
- function Showinfo (id,info)
- {
- $ ("p#" +id). HTML (info);
- }
- </Script>
- </head>
- <body>
- <div data-role="page">
- <div data-role="Content">
- <h2>divice Info</h2>
- <div data-role="Collapsible-set" data-theme="C" data-content-theme="D">
- <div data-role="collapsible">
- <h3 onclick="getInfo (' name ')">name</h3>
- <p id="name"></P>
- </div>
- <div data-role="collapsible">
- <h3 onclick="getInfo (' systemversion ')">systemversion</h3>
- <p id="systemversion"></P>
- </div>
- </div>
- </div>
- </div>
- </body>
- </html>
Web page JS