4

I'm putting app-generated content into a UIWebView, and trying to test that I'm doing it correctly. Here's the HTML string I'm putting into the web view:

@"<html><head></head><body><p>Come, let me clutch thee. I have thee not, and yet I see thee still. Art thou not, fatal vision, sensible to feeling as to sight?</p></body></html>"

And it gets into the web view thus:

[self.webView loadHTMLString: [self HTMLStringForSnippet: model.body] baseURL: nil];

where model.body contains just the <p/> element, and -HTMLStringForSnippet: wraps it into well-formed HTML. In my test, I rely on the answers to this question to retrieve the HTML content of the body via JavaScript:

- (void)testCorrectHTMLLoadedInWebView {
    UIWebView *bodyView = controller.webView;
    NSString *bodyHTML = [bodyView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
    STAssertEqualObjects(bodyHTML, model.body, @"Model body should be used for the web view content");
}

While I can see by stepping through the code that the UIWebView is created correctly and is passed the correct HTML in -loadHTMLString:baseURL:, in the test bodyHTML is empty. So what do I have to do to see the actual content I expect and previously passed to the web view?

Community
  • 1
  • 1

1 Answers1

5

It takes a noticeable time for the UIWebView to render therefore the problem may be that you access the content before it is fully loaded.

Hook on UIWebViewDelegate's webViewDidFinishLoad: method to make sure the content is ready.

Update: Maybe WebViewJavascriptBridge will bring some help.

cSquirrel
  • 1,402
  • 1
  • 9
  • 10
  • 1
    UiWebView hasn't actually finished rendering when webViewDidFinishLoad: is called, just loading, so a lot of content or expensive content may still cause a problem. – Steve Weller Aug 31 '11 at 13:59
  • AFAIK `webViewDidFinishLoad:` is called when `UIWebView` is done loading the input HTML. Sure this doesn't mean all the images/css files/external assets are in place but the question is about accessing the HTML content. – cSquirrel Sep 01 '11 at 09:32
  • what would be the correct way to wait for webViewDidFinishLoad in a unittest? It doesn't seem to work with a simple sleep(10). – nylund Oct 12 '12 at 14:36
  • @nylund - while(!done && [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]); and set done in webViewDidFinishLoad. – Hafthor Jan 02 '14 at 19:01
  • Now that XCTExpectation is available, that is what should be used. I found that using NSRunLoop works fine locally, but fails intermittently once you push it to Xcode Server. Switching to XCTExpectation seemed to fix this. – Saltymule Dec 10 '15 at 14:55