I'm currently using a UIWebView to display a webpage and I'm trying to hide certain elements on the page, then take a screenshot of it. Once I have the image, I will unhide the elements to return the webView back to normal.
Here's my progress so far:
NSString * result1 = [webView stringByEvaluatingJavaScriptFromString:@"(function(){document.getElementById(\"bottom-bar\").style.display = 'none';return document.getElementById(\"bottom-bar\").style.display;})();"];
UIGraphicsBeginImageContextWithOptions(webView.scrollView.contentSize.width, NO, 0.0);
{
CGPoint savedContentOffset = webView.scrollView.contentOffset;
CGRect savedFrame = webView.scrollView.frame;
webView.scrollView.contentOffset = CGPointZero;
webView.scrollView.frame = CGRectMake(0, 0, webView.scrollView.contentSize.width, webView.scrollView.contentSize.height);
[webView.scrollView.layer renderInContext: UIGraphicsGetCurrentContext()];
image = UIGraphicsGetImageFromCurrentImageContext();
webView.scrollView.contentOffset = savedContentOffset;
webView.scrollView.frame = savedFrame;
}
UIGraphicsEndImageContext();
NSString * result2 = [webView stringByEvaluatingJavaScriptFromString:@"document.getElementById(\"bottom-bar\").style.display = 'block';"];
Unfortunately, I'm not able to obtain the desired image.
Instead, I only get an image of the original webView without hiding the element.
When checking the console, I see the correct results "none"
and "block"
, and the element "bottom-bar"
briefly disappears from the screen.
I suspect there may be background threads or queues that affect the execution of
stringByEvaluatingJavaScriptFromString
or renderInContext
. Is there a way for me to get accurate results?
UPDATED: Could GCD and Blocks help me capture the image? I understand that the webView runs JavaScript on a separate webThread and updates the UI on the main thread. Can I somehow wait until the webView finishes updating its UI before taking the screenshot? Is there a way to receive notification from the webThread when it completes a task?