Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WKWebView shows gray background and pdf content gets invisible on viewcontroller switch

I am loading pdf file from main bundle or document directory in WKWebView. It loads perfectly initially but its shows gray background and pdf content gets invisible if I come back to same screen after tab switch in tabbar controller. Here is the code I am using to load

class ViewController: UIViewController {

    @IBOutlet var progressView: UIProgressView!
    @IBOutlet var webView: WKWebView!

    var pdfURLS: URL?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        pdfURLS = Bundle.main.url(forResource: "97_pdf", withExtension: "pdf", subdirectory: nil, localization: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        print("pdfURLS: \(String(describing: pdfURLS))")
    }

    @IBAction func loadAction(_ sender: Any) {
        if let pdfURL = pdfURLS  {
            self.webView.loadFileURL(pdfURL, allowingReadAccessTo: pdfURL.deletingLastPathComponent())
        }
    }
}

Someone has an idea about the issue?enter image description here

Image reference is attached. There is no such kind of problem if I use UIWebView which is deprecated, but I don't want to use deprecated library.

like image 762
Raj Sharma Avatar asked Oct 10 '18 07:10

Raj Sharma


1 Answers

We ran into this problem in Firefox for iOS as well:

https://bugzilla.mozilla.org/show_bug.cgi?id=1516524

I've also referenced this SO post in a WebKit bug:

https://bugs.webkit.org/show_bug.cgi?id=193281

For the time being, we found a workaround:

let previousZoomScale = webView.scrollView.zoomScale
let previousContentOffset = webView.scrollView.contentOffset

if let currentItem = webView.backForwardList.currentItem {
    webView.go(to: currentItem)
}

DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100)) {
    webView.scrollView.setZoomScale(previousZoomScale, animated: false)
    webView.scrollView.setContentOffset(previousContentOffset, animated: false)
}

Basically, we revisit the URL from the back/forward history list which redraws the PDF then we restore the scrollview position/zoom. Its not great, but it works.

like image 122
Justin D'Arcangelo Avatar answered Oct 15 '22 08:10

Justin D'Arcangelo