OC與JavaScript交互#
UIWebView與JavaScript交互的方法是stringByEvaluatingJavaScriptFromString:
OC中調(diào)用JavaScript方法##
[webView stringByEvaluatingJavaScriptFromString:@"first();"];
這里的first()就是JavaScript方法般甲。
OC往JavaScript中注入方法##
- 首先寫(xiě)一個(gè)需要注入的JavaScript方法:
function showAlert() {
alert('this is a alert');
}
- 保存為first.js文件箱玷,拖到Xcode項(xiàng)目里面,然后注入這個(gè)js:
// 讀取js
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"first" ofType:@"js"];
NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];
// 注入js
[webView stringByEvaluatingJavaScriptFromString:jsString];
- 這樣就注入了上面的js,我們隨時(shí)可以調(diào)用js的方法患雏。
JavaScript中調(diào)用OC方法##
原理是利用UIWebView重定向請(qǐng)求拾因,傳一些命令到我們的UIWebView,在UIWebView的代理方法中接收這些命令系冗,并根據(jù)命令執(zhí)行相應(yīng)的OC方法奕扣。這樣就相當(dāng)于在JavaScript中調(diào)用OC的方法。
- 首先寫(xiě)一個(gè)JavaScript方法:
function sendCommand(paramOne,paramTwo) {
var url="testapp:"+paramOne+":"+paramTwo;
document.location = url;
}
function clickLink() {
sendCommand("alert","嗨");
}
- 然后在html里調(diào)用這個(gè)js方法:
"button" value="Click me!" onclick="clickLink()" />
- 最后在UIWebView中截獲這個(gè)重定向請(qǐng)求:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSString *requestString = [[request URL] absoluteString];
NSArray *components = [requestString componentsSeparatedByString:@":"];
if ([components count] > 1 && [(NSString *)[components objectAtIndex:0] isEqualToString:@"testapp"]) {
if([(NSString *)[components objectAtIndex:1] isEqualToString:@"alert"])
{
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:@"Alert from Cocoa Touch" message:[components objectAtIndex:2]
delegate:self cancelButtonTitle:nil
otherButtonTitles:@"OK", nil];
[alert show];
}
return NO;
}
return YES;
}