JS与iOS之间的通信,主要运用两个方法:(PhoneGap框架也是基于此原理)
1、UIWebView的 stringByEvaluatingJavaScriptFromString方法
2、UIWebViewDelegate的
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType方法
[代码]c#/cpp/oc代码:
04 |
NSString *path = [[NSBundle mainBundle] pathForResource:@"jm/info" ofType:@"html"]; |
05 |
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]; |
06 |
[self.webView loadRequest:request]; |
07 |
}<div><h3>[代码]c#/cpp/oc代码:</h3><pre class="brush:c#/cpp/oc;auto-links:false;">#pragma mark - UIWebViewDelegate |
08 |
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType |
10 |
if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/name"]) |
12 |
NSString *info = [[UIDevice currentDevice] name]; |
13 |
NSString *js = [NSString stringWithFormat:@"showInfo(\"name\",\"%@\")",info]; |
14 |
[self.webView stringByEvaluatingJavaScriptFromString:js]; |
17 |
if([request.mainDocumentURL.relativePath isEqualToString:@"/getInfo/systemVersion"]) |
19 |
NSString *info = [[UIDevice currentDevice] systemVersion]; |
20 |
NSString *js = [NSString stringWithFormat:@"showInfo(\"systemVersion\",\"%@\")",info]; |
21 |
[self.webView stringByEvaluatingJavaScriptFromString:js]; |
JS代码:
[代码]js代码:
05 |
<meta charset="utf-8"> |
06 |
<meta name="viewport" content="width=device-width, initial-scale=1"> |
07 |
<link rel="stylesheet" href="jquery.mobile-1.0.css"/> |
08 |
<script type="text/javascript" src="jquery.js"></script> |
09 |
<script type="text/javascript" src="jquery.mobile-1.0.js"></script> |
11 |
function getInfo(name) |
13 |
window.location = "/getInfo/"+name; |
15 |
function showInfo(id,info) |
17 |
$("p#"+id).html(info); |
22 |
<div data-role="page"> |
23 |
<div data-role="content"> |
25 |
<div data-role="collapsible-set" data-theme="c" data-content-theme="d"> |
26 |
<div data-role="collapsible"> |
27 |
<h3 onclick="getInfo('name')">name</h3> |
30 |
<div data-role="collapsible"> |
31 |
<h3 onclick="getInfo('systemVersion')">systemVersion</h3> |
32 |
<p id="systemVersion"></p> |