【发布时间】:2016-07-26 13:57:46
【问题描述】:
如何在objective c中集成JavaScript?
这是我的 JavaScript 代码:
<!DOCTYPE HTML>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="https://maps.micello.com/webmap/v0/micellomap.js"></script>
<script type="text/javascript">
micello.maps.init("ZccEicxOED0xicnQFrnkK7uzXJJUog",mapInit);
function mapInit(strMapID) {
alert("Hello World!"+strMapID);
var mapControl = new micello.maps.MapControl('mapElement');
var mapDataObject = mapControl.getMapData();
mapDataObject.loadCommunity(strMapID);
}
</script>
<style type="text/css">
html, body { height: 100%; width: 100%; margin: 0; overflow: hidden; }
#mapElement{ width:100%; height:100%; }
</style>
</head>
<body>
<div id="mapElement"></div>
</body>
</html>
我在 WebView 的 Objective-C 中使用此 JavaScript 代码。这是我的 Objective-C 代码:
- (void)viewDidLoad {
NSLog(@"strMapID = %@",strMapID);
NSString *path;
NSBundle *thisBundle = [NSBundle mainBundle];
path = [thisBundle pathForResource:@"SomeHTML" ofType:@"html"];
NSURL *instructionsURL = [NSURL fileURLWithPath:path];
[webView loadRequest:[NSURLRequest requestWithURL:instructionsURL]];
}
WebView 委托方法:
-(void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"start");
}
-(void)webViewDidFinishLoad:(UIWebView *)webView1 {
NSLog(@"finish");
[webView1 stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"mapInit(%@)",strMapID]];
//[webView stringByEvaluatingJavaScriptFromString:@"mapInit()"];
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
NSLog(@"Error for WEBVIEW: %@", [error description]);
}
但是在这里,JavaScript alert("Hello World!"+strMapID); 调用了两次。第一次显示正确的 MapID,但第二次显示未定义。
我不知道为什么 alert 会调用 2 次。因此,它在我的 webview 中给了我 500 错误。
请指导我解决我的问题。
提前致谢。
【问题讨论】:
-
这有帮助吗:stackoverflow.com/questions/38198083/…?这不是我的专业领域。
-
谢谢@0aslam0,但这个链接对我没有帮助。
-
我想知道如何将此html代码转换为javascript函数。在此我想通过目标 c 在 mapInit(n) 方法中传递参数。
标签: objective-c uiwebview xcode7 javascriptcore