랭귀지/SWIFT
WKWebView 사용 시 필수 Delegate
유키공
2018. 3. 2. 09:30
WKWebView를 사용한다면 아래의 넷은 반드시 넣어 주어야 한다. 복사->붙여 넣기 후 개발을 시작하면 됩니다.
func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) { let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: { (action) in completionHandler() })) self.present(alertController, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) { let alertController = UIAlertController(title: "", message: message, preferredStyle: .alert) alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: { (action) in completionHandler(true) })) alertController.addAction(UIAlertAction(title: "취소", style: .default, handler: { (action) in completionHandler(false) })) self.present(alertController, animated: true, completion: nil) } func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) { let alertController = UIAlertController(title: "", message: prompt, preferredStyle: .alert) alertController.addTextField { (textField) in textField.text = defaultText } alertController.addAction(UIAlertAction(title: "확인", style: .default, handler: { (action) in if let text = alertController.textFields?.first?.text { completionHandler(text) } else { completionHandler(defaultText) } })) alertController.addAction(UIAlertAction(title: "취소", style: .default, handler: { (action) in completionHandler(nil) })) self.present(alertController, animated: true, completion: nil) } // iOS 9.0 이후 지원 //앱이 백그라운드 상태에서 포그라운드로 돌아 올때 간혹 WKWebView가 하얀 화면으로 되어 있는 경우 public func webViewWebContentProcessDidTerminate(_ webView: WKWebView) { // 중복적으로 리로드가 일어나지 않도록 처리 필요. webView.reload() }