OC与JavaScript交互#
UIWebView与JavaScript交互的方法是stringByEvaluatingJavaScriptFromString:
OC中调用JavaScript方法##
[webView stringByEvaluatingJavaScriptFromString:@"first();"];
这里的first()就是JavaScript方法。
OC往JavaScript中注入方法##
- 首先写一个需要注入的JavaScript方法:
function showAlert() {
alert('this is a alert');
}
- 保存为first.js文件,拖到Xcode项目里面,然后注入这个js:
// 读取js
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"first" ofType:@"js"];
NSString *jsString = [[NSString alloc] initWithContentsOfFile:filePath];
// 注入js
[webView stringByEvaluatingJavaScriptFromString:jsString];
- 这样就注入了上面的js,我们随时可以调用js的方法。
JavaScript中调用OC方法##
原理是利用UIWebView重定向请求,传一些命令到我们的UIWebView,在UIWebView的代理方法中接收这些命令,并根据命令执行相应的OC方法。这样就相当于在JavaScript中调用OC的方法。
- 首先写一个JavaScript方法:
function sendCommand(paramOne,paramTwo) {
var url="testapp:"+paramOne+":"+paramTwo;
document.location = url;
}
function clickLink() {
sendCommand("alert","嗨");
}
- 然后在html里调用这个js方法:
"button" value="Click me!" onclick="clickLink()" />
- 最后在UIWebView中截获这个重定向请求:
- (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;
}