Search code examples
iosswiftuiwebviewfullscreen

UiWebView display in fullscreen


the code below performs the display of a UiViewController, which contains a UiWebView, the UiWebView must be displayed in fullscreen while it is displayed as the image below, I tried in all the ways I know by modifying the storyboard, via swift programming , below you find the view code and the source repo can you explain how to put this ui webview on the fullscreen, do I also attach the simulator image?

Image of screen

Repository Link

ViewController.swift

override func viewDidLoad() {

    super.viewDidLoad()
    let controller = BrowserViewController()
    let navigationController = UINavigationController(rootViewController: controller)
    navigationController.modalPresentationStyle = .overFullScreen
    self.navigationController?.present(navigationController, animated: true, completion: nil)


}

BrowserViewController.swift

import UIKit

func hexStringToRGB(_ hexString: String) -> (red: CGFloat, green: CGFloat, blue: CGFloat) {
    var cString: String = hexString.trimmingCharacters(in: .whitespacesAndNewlines).uppercased()

    if (cString.hasPrefix("#")) {
        cString.remove(at: cString.startIndex)
    }

    if ((cString.count) != 6) {
        return (red: 0.0, green: 0.0, blue: 0.0)
    }

    var rgbValue: UInt32 = 0
    Scanner(string: cString).scanHexInt32(&rgbValue)

    return (
        red: CGFloat((rgbValue & 0xFF0000) >> 16),
        green: CGFloat((rgbValue & 0x00FF00) >> 8),
        blue: CGFloat(rgbValue & 0x0000FF))
}

class BrowserViewController: UIViewController, UIWebViewDelegate {


    //Array che contiene gli url che hanno il permesso di essere visualizzati nella UiWebView
    let urlPermessi = ["web.parktogo.it", "m.facebook.com", "www.facebook.com", "paypal.com", "accounts.google.com"]


    //Definizione della UIWebView
    var myWebView: UIWebView = UIWebView()
    let button = UIButton(type: UIButton.ButtonType.custom)
    //Definizione url home-page
    let urlhomepage = URL (string: "https://web.parktogo.it")
      let dictionatyUnclock = NSDictionary(object: "mozilla/5.0 (iphone; cpu iphone os 7_0_2 like mac os x) applewebkit/537.51.1 (khtml, like gecko) version/7.0 mobile/11a501 safari/9537.53", forKey: "UserAgent" as NSCopying)


    //Check url
    func checkUrl(url: String) {
        if(url == "web.parktogo.it" || url == "https://web.parktogo.it") {
            self.button.isHidden = true
            UserDefaults.standard.register(defaults: dictionatyUnclock as! [String: Any])
        }
        else {
            UserDefaults.standard.register(defaults: dictionatyUnclock as! [String: Any])
            self.button.isHidden = false
        }
    }

    //Funzione che permette di tornare alla pagina precedente nella UiWebView
    @objc func goBack() {
       let request = URLRequest(url: urlhomepage! as URL);
        myWebView.loadRequest(request)
        checkUrl(url: "https://web.parktogo.it")
    }

    //Funzione che si occupa della verifica degli url
    func ValidazioneURL(url: String) -> Bool {
        var check: Bool = true
        if urlPermessi.contains(url) {
            print("Url valido")
        } else {
            print("Url non valido")
            check = false
        }
        checkUrl(url: url)
        return check;
    }


    //Funzione eseguita all'avvio della UIWebView
    override func viewDidLoad() {

        super.viewDidLoad()
        self.view.removeAllConstraints()
        self.view.backgroundColor = UIColor(white: 1, alpha: 0.5)
        self.navigationController?.isNavigationBarHidden = true
        UIApplication.shared.keyWindow?.windowLevel = UIWindow.Level.statusBar

        //
        self.view.backgroundColor = #colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
        myWebView = UIWebView(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height))
        //Istanzio la UIWebView
        myWebView.delegate = self
        //Aggiuge la view all'UIView principale
        self.view.addSubview(myWebView)
        //Questo codice permette di modificare lo useragent per i response della UiWebView
        UserDefaults.standard.register(defaults: dictionatyUnclock as! [String: Any])
        //Visualizzo l'url all'interno della uiwebview
        let request = URLRequest(url: urlhomepage! as URL);
        myWebView.loadRequest(request);
        //Istanza del button che permette di tornare alla schermata precendente
        let image = UIImage(named: "arrow-back-icon.png")
        button.frame = CGRect(x: 0, y: 0, width: 80, height: 150)
        button.setImage(image, for: .normal)
        button.addTarget(self, action: #selector(goBack), for: .touchUpInside)
        //button.backgroundColor = .lightGray
        self.view.addSubview(button)
        checkUrl(url: "https://web.parktogo.it")


    }

//Funzione che viene eseguita ogni volta che verifica gli url presenti nell'array per verificarne la validità
    internal func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        var check: Bool = true
        do {
            //print("Url da verificare = \(request.url!.host!)")
            if navigationType == UIWebView.NavigationType.linkClicked {
                check = ValidazioneURL(url: request.url!.host!)
            }
        }
        catch is Error {

        }
        return check
    }

//Funzione eseguiata all'inzializzazione della webview
    func webView(webView: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebView.NavigationType) -> Bool {
        var check: Bool = true
        print("Url da verificare = \(request.url!.host!)")
        if navigationType == UIWebView.NavigationType.linkClicked {
            check = ValidazioneURL(url: request.url!.host!)
        }
        return check
    }


//Funzione eseguiata al caricamento della webview
    func webViewDidStartLoad(_ webView: UIWebView) {
        print("web view start loading")
    }
    override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(true)
        navigationController?.navigationBar.isHidden = true // for navigation bar hide
       // UIApplication.sharedApplication.statusBarHidden=true// for status bar hide
   }

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

}

Solution

  • Your UIWebView already constrained to superView but myWebView's UIWebBrowserView shows under the safeArea. By the way UIWebView was deprecated, please check the link below.

    Debug View Hierarchy

    Just change the UIWebView to WKWebView

    • Import WebKit
    import WebKit
    

    • Initialize it

    These Italian comments from OP's github repo so knowingly adding them here

    //Definizione della UIWebView
    var myWebView = WKWebView()
    

    • Change loadRequest lines to
    myWebView.load(request)
    

    • In viewDidLoad
    myWebView = WKWebView(frame: CGRect(x: 0, y: 0,
                                                width: view.frame.width,
                                                height: view.frame.height))
    

    And run!


    BONUS

    UIWebView is deprecated -> Apple Docs

    WKWebView documentation -> Apple Docs

    WKWebView usage ->Hackingwithswift