Search code examples
javascriptswiftwebkit

WKUserContentController isn't called when Javascript calls handler


I'm developing IOS App using Webkit, Swift. And I wanna close view controller which shows webkit when my webview logic is done. Using WKUserContentController, I implemented logic.

But It didn't work.

Below is my code.

This is Swift.

import UIKit
import WebKit

class SelfAuthVC: UIViewController, WKNavigationDelegate, WKUIDelegate, WKScriptMessageHandler  {

private var webView: WKWebView!
let contentController = WKUserContentController()
let config = WKWebViewConfiguration()

override func viewWillAppear(_ animated: Bool) {

    contentController.add(self as WKScriptMessageHandler, name: "callbackHandler")

    config.userContentController = contentController


    let preferences = WKPreferences()
    preferences.javaScriptEnabled = true

    config.preferences = preferences
    webView = WKWebView(frame: view.bounds, configuration: config)
    view.addSubview(webView)

    let url = Bundle.main.url(forResource: "auth", withExtension: "html")!
    webView.loadFileURL(url, allowingReadAccessTo: url)
    let request = URLRequest(url: url)

    webView.load(request)
    webView.navigationDelegate = self
    webView.uiDelegate = self

}
override func viewDidLoad() {
    super.viewDidLoad()

}

func webViewDidClose(_ webView: WKWebView) {
    self.navigationController?.popViewController(animated: true)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    webView.evaluateJavaScript("var my_email = '\(UserInfo.shared().email!)'")  { (result, error) in
        guard error == nil else {
            print(error)
            return
        }
    }

}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("didReceive message here")
    if(message.name == "callbackHandler"){
        print("callbackHandler: \(message.body)")
        self.dismiss(animated: true, completion: nil)
        self.navigationController?.popViewController(animated: true)

    }
}

}

Below is JS

<body>
<script language="JavaScript">

IMP.certification({


    min_age: 18
}, function(rsp) {
    if ( rsp.success ) {

        $.ajax({
                method : "POST",
                url : "https://******/user/iamport",
                dataType : 'json',
                data : {
                    imp_uid : rsp.imp_uid,
                    user_email: my_email
                }
         }).done(function(rsp) {
                // 이후 Business Logic 처리하시면 됩니다.

                 (function finish(){
                  window.webkit.messageHandlers.callbackHandler.postMessage("trigger from JS");


                  try {
                  webkit.messageHandlers.callbackHandler.postMessage(
                                                                     'done'
                                                                     );
                  } catch(err) {
                  console.log('The native context does not exist yet');
                  }
                  }())

         });

    } else {
         // Auth failed
        var msg = '인증에 실패하였습니다. 관리자에게 문의하세요';
        msg += '에러내용 : ' + rsp.error_msg;

        alert(msg);
    }
});
</script>
</body>

I think I wrote codes that is needed. But after authorization process, ViewContoller don't disappear. What changes are needed to solve this problem?


Solution

  • I forgot to add this codes.

    config.userContentController = contentController
    contentController.add(self, name: "authAction")