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;
}