8

我需要检查完成加载后的 webview 是否有任何内容。

我需要的很简单。它在我的页面底部有一个小的 webview 条(如广告)

我打电话

NSURLRequest *request=[NSURLRequest requestWithURL:adURL];
[gWebView loadRequest:request];

我收到回调

-(void)webViewDidFinishLoad:(UIWebView *)webView {

但在我的场景中,webview 将返回空,有时它应该有数据。

如果我的服务器 php 文件没有返回任何内容,我不想显示 webview。

如何验证我在回调(或任何其他方式)中收到了一个空页面?

4

4 回答 4

14

如果您正在加载 HTML 页面:

NSString *string = [myWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('html')[0].innerHTML"];
BOOL isEmpty = string==nil || [string length]==0;

或者您可以先加载内容,测试它是否不为空,然后将其提供给 webview。见UIWebView's loadHTMLString:baseURL:loadData:MIMEType:textEncodingName:baseURL:

于 2011-09-28T10:42:54.810 回答
6

这是基于 Jano 的方法,但性能应该更好:

NSString *script = @"document.getElementsByTagName('body')[0].innerHTML.length";
NSString *length = [self.webView stringByEvaluatingJavaScriptFromString:script];

if (length.integerValue > 0) {
    NSLog(@"not empty");
}
于 2016-01-13T15:23:58.033 回答
4

只是回复一个旧帖子,但也许新来的人会发现它很有用。我在同样的问题上苦苦挣扎,发现这个解决方案适用于我的情况:

if (webView.request.URL.absoluteURL == nil) {
        NSLog(@"nil webby");
        NSLog(@"url: %@", webView.request.URL.absoluteURL);
        // Perform some task when the url is nil
    } else {
        NSLog(@"loaded webby");
        NSLog(@"url: %@", webView.request.URL.absoluteURL);
        // Perform some task when the url is loaded
}

您可以从webViewDidFinishLoad:方法调用它。

于 2014-07-03T06:27:56.833 回答
0

就我而言,我希望检测 PDF 是否格式错误。即,由于无法加载 PDF,Web 视图将为空。由于在 iOS 7.1.1 中,我没有收到 didFailLoadWithError 委托回调,因此我需要一种不同的方法来执行此操作。在尝试将 PDF 文档加载到 Web 视图之前,我最终使用了以下方法。

// See https://developer.apple.com/library/ios/documentation/graphicsimaging/conceptual/drawingwithquartz2d/dq_pdf/dq_pdf.html
- (BOOL) isValidPDFDoc: (NSURL *) deviceLocalURL {
    CFStringRef path;
    CFURLRef url;
    CGPDFDocumentRef document;
    size_t count;
    BOOL validDocument = YES;

    // Must use path of URL not absoluteString here.
    path = CFStringCreateWithCString (NULL, [[deviceLocalURL path] cStringUsingEncoding:NSASCIIStringEncoding],
                                      kCFStringEncodingUTF8);
    url = CFURLCreateWithFileSystemPath (NULL, path, // 1
                                         kCFURLPOSIXPathStyle, 0);
    CFRelease (path);
    document = CGPDFDocumentCreateWithURL (url);// 2
    if (!document) {
        validDocument = NO;
    }

    CFRelease(url);
    count = CGPDFDocumentGetNumberOfPages (document);// 3
    if (count == 0) {
        validDocument = NO;
    }

    CGPDFDocumentRelease (document);

    return validDocument;
}
于 2014-06-23T23:49:09.513 回答