-
WKWebView의 DelegateApp/Swift 2017. 2. 20. 11:48
WKWebView는 WKNavigationDelegate와 WKUIDelegate 두가지의 Delegate를 가지고 있습니다.
WKnavigationDelegate - 페이지의 start, loadding, finish, error의 이벤트를 캐치할 수 있으며 웹페이지의 전반적인 상황을 확인할 수 있음
WKUIDelegate - Javascript 이벤트를 캐치하여 동작합니다.
//WKUIDelegate
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960/** Javasccript window open event*/func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {if navigationAction.targetFrame == nil, let url = navigationAction.request.url {if url.description.lowercased().range(of: "http://") != nil || url.description.lowercased().range(of: "https://") != nil || url.description.lowercased().range(of: "mailto:") != nil {UIApplication.shared.openURL(url)}}return nil}@available(iOS 10.0, *)func webView(_ webView: WKWebView, shouldPreviewElement elementInfo: WKPreviewElementInfo) -> Bool {return false}func webViewDidClose(_ webView: WKWebView) {}func webView(_ webView: WKWebView, commitPreviewingViewController previewingViewController: UIViewController) {}/** Javascript Alert Event*/func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {let alertController = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert);alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel) {_ in completionHandler()})let rootViewController: UIViewController = (UIApplication.shared.windows.last?.rootViewController)!rootViewController.present(alertController, animated: true, completion: nil)}/** Javascript Comfirm Event*/func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {let alertController = UIAlertController(title: message, message: nil, preferredStyle: UIAlertControllerStyle.alert);alertController.addAction(UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {_ in completionHandler(false)})alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {_ in completionHandler(true)})let rootViewController: UIViewController = (UIApplication.shared.windows.last?.rootViewController)!rootViewController.present(alertController, animated: true, completion: nil)}func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {}cs // WKNavigationDelegate
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384// 페이지 로딩 시func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {loadingBar.stopAnimating()}/** 페이지 로딩완료 Event*/func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {loadingBar.stopAnimating()myTimer.invalidate()btnRefresh.setImage(image0, for: UIControlState())/* 최근 세션시간 저장 */let delegate = UIApplication.shared.delegate as? AppDelegatedelegate?.sessionRefreshDate = Date()currentURL = (webView.url!.absoluteString)print("Webview did finish load");}func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {loadingBar.startAnimating()}func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {loadingBar.stopAnimating()}/** 쿠키 셋팅을 통한 Session 유지*/func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {if let urlResponse = navigationResponse.response as? HTTPURLResponse,let url = urlResponse.url,let allHeaderFields = urlResponse.allHeaderFields as? [String : String] {let cookies = HTTPCookie.cookies(withResponseHeaderFields: allHeaderFields, for: url)HTTPCookieStorage.shared.setCookies(cookies , for: urlResponse.url!, mainDocumentURL: nil)decisionHandler(.allow)}}/** 페이지 로딩 시 Link Event*/func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {let curUrl = navigationAction.request.url!.absoluteStringHTTPCookieStorage.shared.cookieAcceptPolicy = HTTPCookie.AcceptPolicy.alwaysif ((curUrl.range(of: "phobos.apple.com") != nil) || (curUrl.range(of: "itunes.apple.com") != nil)){goOtherView(navigationAction.request)decisionHandler(.cancel)return}else if((curUrl.hasPrefix("http")) || (curUrl.hasPrefix("https")) || (curUrl.hasPrefix("about")) || (curUrl.hasPrefix("file"))){}else{let strUrl2:String = "http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=369125087&;mt=8"if let strUrl1:URL = URL(string:strUrl2) {if #available(iOS 10.0, *) {UIApplication.shared.open(strUrl1, options: [:], completionHandler: {(success) in//print("Open \(scheme): \(success)")})} else {// Fallback on earlier versionsUIApplication.shared.openURL(strUrl1)}decisionHandler(.cancel)return}}decisionHandler(.allow)}func webView(_ webView: WKWebView, didReceiveServerRedirectForProvisionalNavigation navigation: WKNavigation!) {loadingBar.stopAnimating()}func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {loadingBar.stopAnimating()}cs 'App > Swift' 카테고리의 다른 글
IOS Architecture (0) 2017.07.06 WKWebView 정의 및 로드 (0) 2017.02.20 서브스크립트와 오버라이딩 (0) 2017.02.07 클래스와 구조체 (0) 2017.02.06 열거형 (0) 2017.02.06