[swift3]WKWebviewの画面をキャプチャする方法[UIImage]

2019年8月23日

WKWebviewを画面キャプチャする際に躓いたのでメモ。
まずはスクリーンショットをUIImageに保存する方法 [swift2.0] [UIImage] [UIView] [スクリーンショット]-MILLEN BOXを参考に、画面をキャプチャしてUIImageを返すコードを書いてみます。

func getCapture() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.webView.bounds.size, true, 0)
        webView.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
}

シミュレータで実行すると…

うまくいってますね。しかし実機で実行すると…

スクリーンショットが真っ白です。

そこで、How to capture a full page screenshot of WKWebview?のアンサーを参考に1行変えてみました。

func getCapture() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(self.webView.bounds.size, true, 0)
        self.webView.drawHierarchy(in: self.webView.bounds, afterScreenUpdates: true)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
}


無事実機でもスクリーンショットが表示されました。