案外簡単でした。
UIWebView#stringByEvaluatingJavaScriptFromString
安定のメソッド名の長さ
このメソッドにJSを書きます。
関数を呼び出す一文を文字列で渡します。
webview.stringByEvaluatingJavaScriptFromString("hogeFunction();")
fuga.html(今回はローカルに配置)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script> function hogeFunction(fuga){ document.getElementById('content').innerText = fuga; alert(fuga); } </script> </head> <body> <div id="content" style="font-size:xx-large;"> testtesttesttesttest </div> </body> </html>
ViewController.swift
import UIKit class ViewController: UIViewController, UIWebViewDelegate{ @IBOutlet var webview: UIWebView! override func viewDidLoad() { super.viewDidLoad() //テストとして上記のfuga.htmlをひらく var req = NSURLRequest(URL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("fuga", ofType: "html")!)!) webview.loadRequest(req) } //実行部分 @IBAction func executeHogeFunction(sender: UIButton) { webview.stringByEvaluatingJavaScriptFromString("hogeFunction('\(UIDevice().systemVersion)');") } }
実行
ボタン押下