通过 UIWebView 下载 PDF

Download PDF via UIWebView

我有一个 UIWebView 可以像这样使用 Basic Auth 加载 PDF

NSURL* url = [[NSURL alloc] initWithString:_urlString];
NSString *authStr = [NSString stringWithFormat:@"%@:%@", usr, pwd];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodedStringWithOptions:NSDataBase64Encoding76CharacterLineLength]];
NSMutableURLRequest *mutableRequest = [[NSMutableURLRequest alloc] initWithURL:url];
[mutableRequest setValue:authValue forHTTPHeaderField:@"Authorization"];
[_webView loadRequest:mutableRequest];

有没有办法让我轻松地将此 PDF 文件保存到磁盘上?我试过这个但失败了:

NSData *fileData = [[NSData alloc] initWithContentsOfURL:_webView.request.URL];

我的 URL 看起来像这样:www.domain.com/files/foo.pdf

-initWithContentsOfURL: NSData 的方法执行简单的 HTTP GET,但您需要设置一些授权参数,这就是它失败的原因。

为了避免下载两次数据,您可以使用NSURLSession下载它,保存它,然后使用UIWebView-loadData:MIMEType:textEncodingName:baseURL:加载它。

NSMutableURLRequest *mutableRequest = //Your Custom request with URL and Headers
[[[NSURLSession sharedSession] dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) 
{
    if (data) 
    { 
        //SaveDataIntoDisk
        dispatch_async(dispatch_get_main_queue(), ^(){ 
            [_webView loadData:data MIMEType:@"application/pdf" textEncodingName:@"UTF-8" baseURL:nil]; 
        }); 
    } 
}] resume];

对于Swift:

        let webView = UIWebView()
        let url = URL(string: "")!
        let urlRequest : URLRequest = URLRequest(url: url)
        let task = URLSession.shared.dataTask(with: urlRequest , completionHandler: { (data, urlResponse, error) in

            if (data != nil){
                DispatchQueue.main.async {
                    webView.load(data!, mimeType: "application/pdf", textEncodingName: "UTF-8", baseURL: url)
                }
            }
        })
        task.resume()

另一种方法:- 您可以下载 PDF 文件数据并将其保存在临时目录或您的首选目录中。然后使用保存的目录在 WebView 中打开文件。

        URLSession.shared.dataTask(with: url) { data, response, error in
                    guard let data = data, error == nil else {

                        return
                    }
//MARK:- Now Saving the Document Data into Directory. I am using the temp directory you can change it to yours.
                    let tempDirectory = URL(fileURLWithPath: NSTemporaryDirectory())
                    self.tmpURL = tempDirectory.appendingPathComponent(response?.suggestedFilename ?? "fileName.png")

                     do {
                        try data.write(to: self.tmpURL! )
                     } catch {
                        print(error)
                     }
                     DispatchQueue.main.async {
 //MARK:- Instead of using MIME type and NSData .now you can use the file directory to open the file in WEBView
                         self.webView.loadFileURL(self.tmpURL!, allowingReadAccessTo: self.tmpURL!)     
                      }
                }