Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Take a full screenshot for all webview in swift

Does anyone know how can I take a full screenshot for all my web view using code in swift ( not the screen ! because the webview is long and we must scroll to view the all content ) and share it via UIActivityViewController?

like image 461
Hassan Taleb Avatar asked Jan 16 '15 05:01

Hassan Taleb


1 Answers

Try the following code after web view is loaded:

EDITED: run this code in simulator then check the screenshot.jpeg file in your documents app directory

class ViewController: UIViewController,UIWebViewDelegate {

let fileDirectory = NSSearchPathForDirectoriesInDomains(
    .DocumentDirectory, .UserDomainMask, true)

@IBOutlet weak var webView: UIWebView!

override func viewDidLoad() {


    var urlPath = "http://www.bbc.com/"
    let requestUrl = NSURL(string: urlPath)
    let request = NSURLRequest(URL: requestUrl!)
    webView.loadRequest(request)
    webView.delegate = self

}

func webViewDidFinishLoad(webView: UIWebView) {


    if (!webView.loading){

        var webViewFrame = webView.frame

        webView.frame = CGRectMake(webViewFrame.origin.x, webViewFrame.origin.y, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height)

        UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize, false, 0);
        self.webView.layer.renderInContext(UIGraphicsGetCurrentContext())
        var image:UIImage = UIGraphicsGetImageFromCurrentImageContext();
        var imageData = UIImageJPEGRepresentation(image, 0.7)
        var currentFileName = "screenshot.jpeg"
        var imageFilePath = fileDirectory[0].stringByAppendingPathComponent(currentFileName)
        var imageFileURL = NSURL(fileURLWithPath: imageFilePath)
        imageData.writeToURL(imageFileURL!, atomically: false)
        webView.frame = webViewFrame
    }
}

}
like image 124
Zell B. Avatar answered Oct 27 '22 00:10

Zell B.