How to make Webkit webView with Swift with safe area constraints for iPhone X?


 Last updated on December 06, 2017




1) The storyboard setup should look like the following image:




2) Write the following code in the view controller:



import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate, UIApplicationDelegate, WKNavigationDelegate {

  @IBOutlet weak var webViewContainer: UIView!

  let requestURLString = "http://google.com/“

  var webView: WKWebView!

  override func viewDidLoad() {

  super.viewDidLoad()
   let webConfiguration = WKWebViewConfiguration()

   let customFrame = CGRect.init(origin: CGPoint.zero, size: CGSize.init(width: 0.0, height: self.webViewContainer.frame.size.height))
   self.webView = WKWebView (frame: customFrame , configuration: webConfiguration)
   webView.translatesAutoresizingMaskIntoConstraints = false
   self.webViewContainer.addSubview(webView)
   webView.topAnchor.constraint(equalTo: webViewContainer.topAnchor).isActive = true
   webView.rightAnchor.constraint(equalTo: webViewContainer.rightAnchor).isActive = true
   webView.leftAnchor.constraint(equalTo: webViewContainer.leftAnchor).isActive = true
   webView.bottomAnchor.constraint(equalTo: webViewContainer.bottomAnchor).isActive = true
   webView.heightAnchor.constraint(equalTo: webViewContainer.heightAnchor).isActive = true

   webView.uiDelegate = self
   webView.navigationDelegate = self
   webView.scrollView.bounces = false
   self.openUrl()
 }

  func openUrl() {
   let url = URL (string: requestURLString)
   let request = URLRequest(url: url!)
   webView.load(request)
  }
}