我目前有成功加載html文件的網頁視圖。我有一個確實的方法,這看起來像:使用本地iOS應用程序調用Javascript函數使用變量
- (EmailView *)loadHTMLIntoEmailView:(EmailView *)emailView
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"inlineAttachmentTemplate" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:path];
NSString *resourceURL = [[NSBundle mainBundle] resourcePath];
resourceURL = [resourceURL stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
resourceURL = [resourceURL stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *baseURL = [NSURL URLWithString:[NSString stringWithFormat:@"file:/%@//",resourceURL]];
[emailView.webView loadData:htmlData MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:baseURL];
return emailView;
}
HTML文件我的樣子:
<!doctype html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="inlineAttachmentTemplateStyling.css">
<script>
function myFunction()
{
document.write("Hello from my html file!!!!");
}
</script>
</head>
<body id="body">
<div id="container">
<img id="testImage" src="fauxImageAttachment2.JPG" />
</div><!-- #container -->
</body>
</html>
這工作,因爲圖像顯示在網頁視圖。如果我將document.write從函數中取出,並將其直接放置在腳本標記中,則文本將出現在web視圖中。但是,我需要能夠調用允許文本顯示在webview中的函數(從我的Objective C方法),最終我還需要將此函數傳遞給一些變量。目前,我甚至無法弄清楚如何讓JavaScript函數被調用。
我看了看這個例子中,Can you call a javascript function from native code (not in a callback) using PhoneGap and iOS?,並嘗試添加以下行到我的目標C法:
[emailView.webView stringByEvaluatingJavaScriptFromString:@"myFunction()"];
但這並不調用函數...或者至少文本沒有出現在webview。
我是一個相當新手的程序員,對JavaScript根本不瞭解 - 任何人都可以突出顯示我做錯了什麼?