通过UIWebView下载PDF

时间:2017-09-05 09:37:54

标签: ios objective-c pdf 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];

我的网址如下所示:www.domain.com/files/foo.pdf

3 个答案:

答案 0 :(得分:2)

-initWithContentsOfURL:的{​​{1}}方法执行简单的HTTP GET,但您需要设置一些授权参数,以及它失败的原因。

为避免下载两倍数据,您可以使用NSData下载,保存并使用NSURLSession -loadData:MIMEType:textEncodingName:baseURL:加载数据。

UIWebView

答案 1 :(得分:1)

对于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()

答案 2 :(得分:0)

另一种方法:-您可以下载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!)     
                      }
                }