Check if UIWebview is displaying PDF

2020-07-18 02:51发布

问题:

To be clear, my question is not asking how to display a PDF in a UIWebview. I want to check if the user has navigated to a PDF (.pdf) document from some website or link. That way I can show more options to the user, like saving the PDF or printing it. What's the best way to check if the UIWebView's content is a PDF?

回答1:

You can check the MIME type too, for a slightly longer journey:

@property (nonatomic, strong) NSString *mime;

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
   mime = [response MIMEType];
}

- (BOOL)isDisplayingPDF {
    NSString *extension = [[mime substringFromIndex:([mime length] - 3)] lowercaseString];

    return ([[[self.webView.request.URL pathExtension] lowercaseString] isEqualToString:@"pdf"] || [extension isEqualToString:@"pdf"]);
}


回答2:

It's a long trip, but I think this will work ...

BOOL isPdf = [[[self.webView.request.URL pathExtension] lowercaseString]
                 isEqualToString:@"pdf"];