본문 바로가기

프로그래밍 TIP/Swift

[Swift] WKWebView 에 URL 변경 후 로딩하기

 저는 안드로이드 개발자입니다. 

하이브리드 앱을 주로 개발하기 때문에 Webview를 많이 사용하는데요.

안드로이드의 경우 WebView 클라이언트들을 상속한 서브클래스들로 URL을 처리하기 쉬운데요 

iOS의 경우 똑 같은 기능을 구현하려고 하니 머리가 아프네요 

구글링 하는 방법도 모르겠고, 해서 직접 구현한 방법을 공유 하고자 합니다.

WKWebView를 사용 기준으로 하겠습니다. 기본적은 델리게이트를 바인딩 한 후 

 

가장 중요한 델리게이트는 WKNavigationDelegate 이며 아래 델리게이트 메소드 입니다.

 

 /*! @abstract Decides whether to allow or cancel a navigation.

     @param webView The web view invoking the delegate method.

     @param navigationAction Descriptive information about the action

     triggering the navigation request.

     @param decisionHandler The decision handler to call to allow or cancel the

     navigation. The argument is one of the constants of the enumerated type WKNavigationActionPolicy.

     @discussion If you do not implement this method, the web view will load the request or, if appropriate, forward it to another application.

     */

    @available(iOS 8.0, *)

 

    optional public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void)

소스 코드는 아래 공유합니다. 주석을 잘 읽어보시면 이해가 되실겁니다.

public func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Swift.Void) {

        //현재 로딩 URL을 가져옵니다.

        let loadUrl : String = navigationAction.request.url!.absoluteString

        //변경할려는 URL의 파라미터가 있는지 확인합니다.

        if !(let isAppSettingLoad == loadUrl.contains("appSetting")) {

            //없으면 해당 파라미터를 추가하여 URL을 구성합니다.

            let fixedUrl : String = String("\(loadUrl)&appSetting=Y")

            let url : URL? = URL(string:fixedUrl)

            //해당 URL로 로딩시킵니다.

            webView.load(URLRequest(url: url!))

            //! 중요 아래 핸들러를 꼭 호출하되 return 시켜서 아래의 블럭들은 실행되지 않도록 처리해줍니다.

            decisionHandler(.allow)

            return

        }

        decisionHandler(.cancel)

 

    }

 

 

'프로그래밍 TIP > Swift' 카테고리의 다른 글

[Swift] Array Dictionary 사용  (0) 2019.04.04