1

Hi everybody i'm stuck with trying to convert my UIWebView, in which i'm currently displaying a ppt file, to a bitmap image.

I have this code:

UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 768, 708)];

NSString *path = [[NSBundle mainBundle] pathForResource:documentName ofType:nil];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];

NSLog(@"Ouverture du contexte image");
UIGraphicsBeginImageContext(webView.bounds.size);
[webView.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

The webview is actually well displayed but I didn't manage to create it's render to an image, If anybody knows where is the issue ;) Thankss

Bobyblanco
  • 123
  • 12

1 Answers1

2

There's nothing wrong with your screenshot-taking code — you're just using it prematurely.

[webView loadRequest:request]; initiates an asynchronous client request. That means you're taking a screenshot of webView before it even loads its contents.

Move your screenshot-taking code to UIWebViewDelegate's method webViewDidFinishLoad:. Of course you're going to have to assign a delegate to your webView to achieve this.

ЯegDwight
  • 24,821
  • 10
  • 45
  • 52
Rok Jarc
  • 18,765
  • 9
  • 69
  • 124
  • But i don't really understand, because my powerpoint file is displayed correctly and the image is also created but all in white with no content :s What you just said about `[webView loadRequest:request];` isn't related to the conversion to image i guess, it is just use to display the powerpoint isn't it ? But i'm going to have a look on what you said thanks ;) – Bobyblanco Apr 20 '12 at 13:19
  • You're welcome! When you call `loadRequest:` webView starts loading it's contents. But you are trying to make a screenshot immediatly - that's why you're getting blank screenshot. There's a delay between calling `loadRequest:` and webView actually being populated. You should wait until contents is loaded. That is why screenshot-taking code should be moved to `webViewDidFinishLoad:` – Rok Jarc Apr 20 '12 at 13:28
  • ahhhh ok! :) But do i have to implement another class for the delegate? I'm in a split view template and this function is called from the detail view controller (so a uiviewcontroller). I guess the didfinishlaunching method in the controller can't solve my problem? – Bobyblanco Apr 20 '12 at 14:11
  • Delegate can be any object - if your webView is a subview of some UIViewController it would be best to make that UIViewController a delegate of webView. This link might help you: http://stackoverflow.com/questions/4342006/set-a-delegate-for-uiwebview – Rok Jarc Apr 20 '12 at 14:26