ios – Is there any way to disable gestures in WKWebView?

I created a separate uiView file, put WKWebview in the uiView, and applied it to the UIView Custom Class in the ViewController.

I want to disable gestures in WebView. Currently doing that action.enter image description here

I want to take measures to prevent the swipe action of the attached gif.

The code I used for webkit is as follows. I hope you can help

import UIKit

import WebKit

class WebPlayerViewHolder: UIView, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler {

@IBOutlet var viewHolder: UIView!
@IBOutlet weak var webView: WKWebView!

var urlString = ""
var jsInterface = ""

override init(frame: CGRect) {
    super.init(frame: frame)
    initView()
}

required init?(coder: NSCoder) {
    super.init(coder: coder)
    initView()
}

private func initView() {
    let bundle = Bundle(for: type(of: self))
    bundle.loadNibNamed("WebPlayerViewHolder", owner: self, options: nil)
    addSubview(viewHolder)
    
    webView.scrollView.isScrollEnabled = false
    webView.isUserInteractionEnabled = false
}

func initWebView() {
  
    let configuration = createConfiguration()
    
    addJSListener(configuration: configuration)
    
    webView = createWebView(configuration: configuration)
    
    viewHolder.addSubview(webView)
    webView.didMoveToSuperview()
    
    DLogUtil.debug(tag: #file, content: urlString)
    let url = URL(string: urlString)
    let request = URLRequest(url: url!)
    webView.load(request)
}

private func createConfiguration() -> WKWebViewConfiguration {
    let preferences = WKPreferences()
    preferences.javaScriptCanOpenWindowsAutomatically = true
    preferences.javaScriptEnabled = true
  
    let configuration = WKWebViewConfiguration()
    configuration.preferences = preferences
    
    // 메모리에서 랜더링 후 보여줌 Defalt = false
    // true 일경우 랜더링 시간동안 Black 스크린이 나옴
    configuration.suppressesIncrementalRendering = false
    
    // 기본값 false : HTML5 Video 형태로 플레이
    // true  : native full-screen play
    configuration.allowsInlineMediaPlayback = false
    
    // whether AirPlay is allowed.
    configuration.allowsAirPlayForMediaPlayback = false
    
    // 기본값 : true
    // whether HTML5 videos can play picture-in-picture.
    configuration.allowsPictureInPictureMediaPlayback = false
    
    // LocalStorage 사용하도록 설정
    configuration.websiteDataStore = WKWebsiteDataStore.default()

    // 기본값 : true
    // true : 사용자가 시작 , false : 자동시작
    configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypes.all
    
    return configuration
}

private func createWebView(configuration: WKWebViewConfiguration) -> WKWebView {
    
    webView.navigationDelegate = self
    webView.uiDelegate = self
    
    webView.scrollView.scrollsToTop = true
    webView.scrollView.bounces = false
    webView.scrollView.pinchGestureRecognizer?.isEnabled = false
    webView.translatesAutoresizingMaskIntoConstraints = false
    webView.scrollView.showsHorizontalScrollIndicator = false
    webView.backgroundColor = UIColor.white
    
    return webView
}

private func addJSListener(configuration: WKWebViewConfiguration) {
    
    guard jsInterface != "" else {
        return
    }
    
    DLogUtil.debug(tag: #file, content: "addJSListener (jsInterface)")
    
    let userContentController = WKUserContentController.init()
    userContentController.add(self, name: jsInterface)
    
    configuration.userContentController = userContentController
}

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    
    DLogUtil.debug(tag: #file, content: "(message.body) (message.name) (message.frameInfo.request)")
    
    var dict: Dictionary<String, Any> = parsingJSInterfaceMessage(message: message)
    dict["target"] = target
    DLogUtil.debug(tag: #file, content: dict)
    
}

private func parsingJSInterfaceMessage(message: WKScriptMessage) -> Dictionary<String, Any> {
    
    DLogUtil.debug(tag: #file, content: "parsingJSInterfaceMessage (message)")
    
    guard message.body as! String != "" else {
        return Dictionary<String, Any>()
    }
    
    let infoArray = (message.body as! String).split(separator: ",")
    
    var dict: Dictionary<String, Any> = Dictionary<String, Any>()
    
    for info in infoArray {
        
        let infoKV = info.replacingOccurrences(of: " ", with: "").split(separator: ":")
        
        let key = infoKV[0]
        var value: String
        if infoKV.count > 1 {
            value = String(infoKV[1])
        }
        else {
            value = ""
        }
       
        dict[String(key)] = value
        
    }
    
    return dict
}

func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
    
    DLogUtil.debug(tag: #file, content: "check create (navigationAction.targetFrame == nil) (!(navigationAction.targetFrame?.isMainFrame ?? false))")
    DLogUtil.debug(tag: #file, content: navigationAction.request.url?.absoluteString ?? "empty url")
    
    self.webView.willMove(toSuperview: nil)
    self.webView.removeFromSuperview()
    self.webView = nil
    self.webView = createWebView(configuration: configuration)
    
    //viewCelll.addSubview(self.webView)
    self.webView.didMoveToSuperview()
    return self.webView
    
}

// can jump or not
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {

    let scheme = navigationAction.request.url?.scheme ?? ""
    let navigationUrlString = navigationAction.request.url?.absoluteString ?? ""
    
    DLogUtil.debug(tag: #file, content: "can jump or not (navigationUrlString)")
    
    if navigationUrlString == "" {
        decisionHandler(.allow)
        return
    }
    
    if navigationUrlString.hasPrefix("https://itunes.apple.com") {
        
        //스토어 연결(OS에서 처리)
        UIApplication.shared.open(URL(string: navigationUrlString)!)
        
        //웹뷰 내 페이지 이동 안하도록 설정(PolicyCancel)
        decisionHandler(.cancel)
        return
    }
    else if navigationUrlString.hasPrefix("tauthlink") ||
                navigationUrlString.hasPrefix("ktauthexternalcall") ||
                navigationUrlString.hasPrefix("upluscorporation") ||
                navigationUrlString.hasPrefix("niceipin2") {
        //외부 앱 Scheme로 URL이 시작되는 경우
        //tauthLink(SKT PASS 인증앱)
        //ktauthexternalcall(KT PASS 인증앱)
        //upluscorporation(LGU+ PASS 인증앱)
        //회원사에서 추가로 연동하고 싶은 앱스키마가 있다면 or 조건에 추가 해주세요. (예시 : niceipin2 )
        
        //앱 실행
        UIApplication.shared.open(URL(string: navigationUrlString)!)
        
        //웹뷰 내 페이지 이동 안하도록 설정(PolicyCancel)
        decisionHandler(.cancel)
        return
    }
            
    DLogUtil.debug(tag: #file, content: "here")
    
    decisionHandler(.allow)
    return
}


func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
    decisionHandler(.allow)
}

func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
    DLogUtil.debug(tag: #file, content: "start (webView.url?.absoluteString ?? "empty url")")
}

private func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
    DLogUtil.debug(tag: #file, content: "fail (webView.url?.absoluteString ?? "empty url")")
}

func webView(_ webView: WKWebView, didCommit navigation: WKNavigation!) {
    DLogUtil.debug(tag: #file, content: "commit (webView.url?.absoluteString ?? "empty url")")
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    DLogUtil.debug(tag: #file, content: "finish (webView.url?.absoluteString ?? "empty url")")
    NotificationUtil.post(name: "init")
}

deinit {
    DLogUtil.debug(tag: #file, content: "deinit")
    
    if webView != nil {
        
        if jsInterface != "" {
            webView!.configuration.userContentController.removeScriptMessageHandler(forName: jsInterface)
        }
       
        webView!.removeFromSuperview()
        webView = nil
    }
}

}

Leave a Comment