스토리보드
test.html
<h2>Welcome</h2>
<script type="text/javascript">
function LoadComplete(){
alert("loading Complete!");
}
</script>
전체 소스
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler
{
@IBOutlet var containerView: UIView!
var webView: WKWebView!
override func loadView() {
super.loadView()
let contentController = WKUserContentController()
let config = WKWebViewConfiguration()
let userScript = WKUserScript(
source: "LoadComplete()",
injectionTime: WKUserScriptInjectionTime.atDocumentEnd,
forMainFrameOnly: true
)
contentController.addUserScript(userScript)
config.userContentController = contentController
webView = WKWebView(
frame: self.containerView.bounds,
configuration: config
)
webView.uiDelegate = self
self.view.addSubview(webView)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
guard let localFilePath = Bundle.main.path(forResource: "test", ofType: "html")
else {
print("path is nil")
return
}
let url = URL(fileURLWithPath: localFilePath)
let request = URLRequest(url: url)
webView.load(request as URLRequest)
}
public func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage
message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping() -> Void) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let otherAction = UIAlertAction(title: "OK", style: .default, handler: {action in completionHandler()})
alert.addAction(otherAction)
self.present(alert, animated: true, completion: nil)
}
// Web View에서 웹 컨텐츠를 받기 시작할 때 호출된다.
func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
}
// 웹 컨텐츠가 Web View로 로드되기 시작할 때 호출된다.
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
}
@available(iOS 8.0, *)
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
}
}
실행결과
'프로그램 > iOS' 카테고리의 다른 글
WKWebView 를 이용해서 로드된 웹페이지의 JavaScript 함수 호출 (0) | 2020.01.09 |
---|---|
WKWebView 를 이용해서 로컬 HTML 파일 로딩. javascript --> native (0) | 2020.01.06 |
WKWebView 를 이용해서 로컬 HTML 파일 로딩 (0) | 2020.01.01 |
WKWebView 를 이용해서 웹사이트 호출 (0) | 2019.12.31 |
로컬 HTML파일을 UIWebView, WKWebView에 표시하기 (0) | 2019.12.27 |