I'm trying to show a UIWebView with a GIF in it, but only once the GIF has loaded.

I load the GIF as follows:

    self.GIFWebView = [[UIWebView alloc] init];
    self.GIFWebView.delegate = self;

    NSString *html = [NSString stringWithFormat:@"<html><head></head><body><img src=\"%@\"></body></html>", post.url];
    [self.GIFWebView loadHTMLString:html baseURL:nil];

Where post is just an object with some properties such as the URL for the GIF.

Then in webViewDidFinishLoad: I show the web view:

- (void)webViewDidFinishLoad:(UIWebView *)webView {
    NSLog(@"%f", webView.scrollView.frame.size.width);
    NSLog(@"%@", [webView.request.URL absoluteString]);
}

I get "0" and "about:blank" for the NSLogs each time, however.

Why does it not load the GIF properly?

1

There are 1 answers

6
Caleb On

I get "0" and "about:blank" for the NSLogs each time, however.

Not surprising. You're telling the web view to load HTML that you're providing in a string rather than giving it a request. The URL that you're logging is the request URL, and since there's no request, there's no request URL.

Why does it not load the GIF properly?

Possibly because you're misusing the URL object. Look at the code:

NSString *html = [NSString stringWithFormat:@"<html><head></head><body><img src=\"%@\"></body></html>", post.url];

We can't tell what type post.url is, but it's probably NSURL*. You're probably passing a NSURL into the format string, and that may not produce the result you're looking for. Try passing in a string like [post.url absoluteString] instead of the actual NSURL object.

Also, you might want to log the value of html right after you create it so that you can check the full HTML that you're sending to the web view.

Update: Some additional things to check:

  1. Are you running the code in question on the main thread?
  2. Is the thread's run loop getting time?
  3. Have you tried setting a non-nil base URL?
  4. If the web view's delegate has a -webView:shouldStartLoadWithRequest: method, does it return YES?
  5. What happens if you use a constant string that includes the HTML you want and the hard-coded URL instead of constructing the string with +stringWithFormat:?
  6. Is the test device connected to the network? (Sometimes it's the simplest thing that gets you.)
  7. Does it work correctly if you use a different image? I notice that the URL you're using is for an animated .gif file, try a non-animated .gif or a .jpg image instead.

Update 2: The problem lies in your creation of the web view. Look at the very first line in the code that you showed:

self.GIFWebView = [[UIWebView alloc] init];

That looks okay for a typical object, but -init is not the designated initializer for a view. You should use -initWithFrame: instead. The image loads fine in your sample project when I change the code in your project to use the right initializer:

UIWebView *GIFWebView = [[UIWebView alloc] initWithFrame:self.view.bounds];