본문 바로가기
네이티브/Ios

Ios 웹뷰 alert, confirm 띄우기

by 우보틀 2022. 1. 23.

웹뷰에서 javascript로 된 alert와 confirm을 띄우려면 코드를 추가해주어야 합니다.

 

alert와 confirm의 경우 

각각 webview에 정의되어 있는 인스턴스 메소드들을 선언해주어야 합니다.

viewController 내부에 선언해주면 됩니다.

 

UIAlertController에서 preferredStyle을 커스텀 해줄수 있습니다.

.alert와 .actionSheet 두개의 형식이 있습니다. 

원하는 형식을 선택해서 보여주고 싶은 형식을 보여주면 됩니다!

 

alert

func webView(_ webView: WKWebView, runJavaScriptAlertPanelWithMessage message: String,
             initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping () -> Void) {
    let alertController = UIAlertController(title: message, message: nil,
                                            preferredStyle: .alert);

    alertController.addAction(UIAlertAction(title: "확인", style: UIAlertActionStyle.cancel) {
        _ in completionHandler()}
    );

    self.present(alertController, animated: true, completion: {});
}

preferredStyle: .alert
preferredStyle: .actionSheet

confirm

func webView(_ webView: WKWebView, runJavaScriptConfirmPanelWithMessage message: String, initiatedByFrame frame: WKFrameInfo,
             completionHandler: @escaping (Bool) -> Void) {

    let alertController = UIAlertController(title: nil, message: message, preferredStyle: .actionSheet)

    alertController.addAction(UIAlertAction(title: "네", style: .default, handler: { (action) in
        completionHandler(true)
    }))

    alertController.addAction(UIAlertAction(title: "아니오", style: .default, handler: { (action) in
        completionHandler(false)
    }))

    present(alertController, animated: true) {}

}

preferredStyle: .alert
preferredStyle: .actionSheet

 

 

https://developer.apple.com/documentation/webkit/wkuidelegate/1537406-webview

 

Apple Developer Documentation

 

developer.apple.com