본문 바로가기
모바일앱/iOS

앱과 웹간 소통방법(1)

by GeekCode 2022. 11. 18.
반응형

 

앱과 웹간 소통방법(1)

 

 

 

웹뷰 디버깅

사파리 - 관리자도구를 누르면 콘솔창이 보인다.

이 콘솔창에 특정 키를 넣어 입력할 수 있다

 

 

웹뷰 새로고침

  • 좌측 상단의 새로고침 버튼
  • 콘솔창 입력 → 강력 새로고침 : window.location.reload()
  • 콘솔에서 네이티브로 message를 보내는 테스트도 가능
    • 아래 메시지를 입력하고 엔터를 치면, Xcode에서 메시지 수신 확인이 가능
window.webkit.messageHandlers.HandlerName.postMessage

window.webkit.messageHandlers.HandlerName.postMessage('test')

이 방법은 나중에 소개하도록 하겠습니다!

 

 

 

1. 콘솔에서 네이티브로 alert보내기

window.alert("GeekCode")

VC에서 runJavaScriptAlertPanelWithMessage 함수를 구현하지않으면 앱이 죽을 수 있다.

 

 

스크린샷 2022-11-18 오후 2 06 09스크린샷 2022-11-18 오후 2 07 54

 

 

2. 콘솔에서 웹뷰내 tag에 접근하기

google의 intput의 placeholder도 채워줄 수 있다.

getElementsByTagName(name); 함수는 특정 tag명을 가지고 있는 dom 요소에 접근하는 메서드이다.

document.getElementsByTagName('input')[0].placeholder = "GeekCode"

스크린샷 2022-11-18 오후 1 34 02

 

 

 

 

디버그창에서 스키마 보내기

세팅되어있는 스키마를 디버그창에서 보내면서 테스트를 할 수가 있다.

location.href=”<내용>”

아래처럼 세팅되어있다면 바코드스캔을 실행하기위해 url에 “barcodeScan”을 입력해 보내면 실행된다.

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

            guard let currWholeUrl = navigationAction.request.url else { decisionHandler(.cancel)
                        return
                    }

            let url = currWholeUrl.absoluteString
                    if url.contains("barcodeScan") {
                        // 바코드 스캔 로직
                        let msg = "barcodeScan Signal is Cached"
                        let alertController = UIAlertController(title: "", message: msg, preferredStyle: .alert)
                        let cancelAct = UIAlertAction(title: "cancel", style: .cancel) { UIAlertAction in
                            print("cancel")
                        }
                        let confirmAct = UIAlertAction(title: "confirm", style: .default) { UIAlertAction in
                            print("okay")
                        }
                        [ cancelAct,confirmAct ].forEach { alertController.addAction($0) }
                        present(alertController, animated: true, completion: nil)
                    }
}

스크린샷 2022-11-18 오후 3 02 19

 

 

 

웹에서 앱으로 얼럿 띄우기

  • UIDelegate를 이용하는 방법
  • 브릿지를 이용해 WKScriptMessageHandler 이용하는 방법

 

Alert수신

위에 테스트코드로 작성한것처럼 특정 스키마가 들어올때, 얼럿을 구현할 수있지만.

직접적으로 웹에서 띄울수 있는 Alert은 alert, confirm, prompt 3가지가 있다.

WkWebView에 UIDelegate를 위임시켜주고 아래 함수들을 세팅한다.

  • runJavaScriptAlertPanelWithMessage
  • runJavaScriptConfirmPanelWithMessage
  • runJavaScriptTextInputPanelWithPrompt
extension ViewController: WKUIDelegate{

    func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "확인", style: .default) { (action) in
            completionHandler()
        }
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (Bool) -> Void) {
        let alert = UIAlertController(title: "", message: message, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "확인", style: .default) { (action) in
            completionHandler(true)
        }
        let cancelAction = UIAlertAction(title: "취소", style: .default) { (action) in
            completionHandler(false)
        }
        alert.addAction(okAction)
        alert.addAction(cancelAction)
        self.present(alert, animated: true, completion: nil)
    }

    func webView(_ webView: WKWebView, runJavaScriptTextInputPanelWithPrompt prompt: String, defaultText: String?, initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping (String?) -> Void) {
        let alert = UIAlertController(title: "", message: prompt, preferredStyle: .alert)
        let okAction = UIAlertAction(title: "확인", style: .default) { (action) in
            if let text = alert.textFields?.first?.text {
                completionHandler(text)
            } else {
                completionHandler(defaultText)
            }
        }
        alert.addAction(okAction)
        self.present(alert, animated: true, completion: nil)
    }

}

구현을 위해서는 AlertController로 넘어온 Message와 Completion을 이용해 구현하면 된다.

 

 

 

참고:

반응형

'모바일앱 > iOS' 카테고리의 다른 글

refresh control 사용하기  (0) 2022.12.13
세로모드 고정  (0) 2022.11.28
Date로 두 개의 시간차 구하기  (0) 2022.11.24
간단한 MVVM구조 예제  (0) 2022.11.23
여러가지 접근권한요청  (0) 2022.11.17
WKWebView - Navigation Delegate함수  (0) 2022.11.15
전통적인 MVC구조로 HTTP사용하기  (0) 2022.11.14
preview, canvas 위치 이동시키기  (0) 2022.11.07