【问题标题】:How to download PDF and store it locally on iPhone?如何下载 PDF 并将其存储在 iPhone 本地?
【发布时间】:2011-01-14 15:49:04
【问题描述】:

我能够成功地从网站查看 PDF。我希望能够将该 PDF 下载到设备上,然后在本地访问该文件。

当应用程序打开时,它会检查在线 PDF 的日期。如果它比本地存储的 PDF 更新,则应用程序将下载新的,否则将打开本地存储的 PDF。

我目前使用的代码:

PDFAddress = [NSURL URLWithString:@"http://www.msy.com.au/Parts/PARTS.pdf"];
request = [NSURLRequest requestWithURL:PDFAddress];
[webView loadRequest:request];
webView.scalesPageToFit = YES;

我怎样才能做到这一点?

【问题讨论】:

    标签: iphone pdf iphone-sdk-3.0 uiwebview


    【解决方案1】:

    我找到了一种我自己尝试过的方法:

    // Get the PDF Data from the url in a NSData Object
    NSData *pdfData = [[NSData alloc] initWithContentsOfURL:[
        NSURL URLWithString:@"http://www.example.com/info.pdf"]];
    
    // Store the Data locally as PDF File
    NSString *resourceDocPath = [[NSString alloc] initWithString:[
        [[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent]
            stringByAppendingPathComponent:@"Documents"
    ]];
    
    NSString *filePath = [resourceDocPath 
        stringByAppendingPathComponent:@"myPDF.pdf"];
    [pdfData writeToFile:filePath atomically:YES];
    
    
    // Now create Request for the file that was saved in your documents folder
    NSURL *url = [NSURL fileURLWithPath:filePath];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    
    [webView setUserInteractionEnabled:YES];
    [webView setDelegate:self];
    [webView loadRequest:requestObj];
    

    这将在本地存储您的 PDF 并将其加载到您的 UIWebView 中。

    【讨论】:

    • 我正在使用这个网址**developer.apple.com/iphone/library/documentation/UIKit/…**。我应该在 stringByAppendingPathComponent:myPDF.pdf 中传递什么???我应该通过哪个pdf名称?请帮帮我。
    • 抱歉回复晚了,您需要将要存储的 PDF 的名称为 as,以及扩展名“.pdf”作为字符串传递。
    • 是的,我明白了。非常感谢您的回复和帮助。为它 +1。
    • 如何找回它??
    • @RVN 我已使用此代码并保存了 PDF。但是当我在 iPad 上打开 adobe reader 应用程序时,它什么也没显示。是的,我在那里没有得到任何 pdf 文件吗? pdf 保存在哪里?
    【解决方案2】:

    在 Swift 4.1 中

    // Url in String format
    let urlStr = "http://www.msy.com.au/Parts/PARTS.pdf"
    
    // Converting string to URL Object
    let url = URL(string: urlStr)
    
    // Get the PDF Data form the Url in a Data Object
    let pdfData = try? Data.init(contentsOf: url!)
    
    // Get the Document Directory path of the Application
    let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
    
    // Split the url into a string Array by separator "/" to get the pdf name
    let pdfNameFromUrlArr = urlStr.components(separatedBy: "/")
    
    // Appending the Document Directory path with the pdf name
    let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrlArr[
        pdfNameFromUrlArr.count - 1])
    
    // Writing the PDF file data to the Document Directory Path
    do {
        _ = try pdfData.write(to: actualPath, options: .atomic) 
    }catch{
    
        print("Pdf can't be saved")
    }
    
    // Showing the pdf file name in a label
    lblPdfName.text = pdfNameFromUrlArr[pdfNameFromUrlArr.count - 1]
    
    // URLRequest for the PDF file saved in the Document Directory folder
    let urlRequest = URLRequest(url: actualPath)
    
    webVw.isUserInteractionEnabled = true
    webVw.delegate = self
    webVw.loadRequest(urlRequest)
    

    如果您想将 Pdf 保存在主文档目录中的特定文件夹/目录中

    let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL
    
    // The New Directory/folder name
    let newPath = resourceDocPath.appendingPathComponent("QMSDocuments")
    
    // Creating the New Directory inside Documents Directory
    do {
        try FileManager.default.createDirectory(atPath: newPath.path, withIntermediateDirectories: true, attributes: nil)
    } catch let error as NSError {
        NSLog("Unable to create directory \(error.debugDescription)")
    }
    
    // Split the url into a string Array by separator "/" to get the pdf name
    pdfNameFromUrlArr = urlStr.components(separatedBy: "/")
    
    // Appending to the newly created directory path with the pdf name
    actualPath = newPath.appendingPathComponent(pdfNameFromUrlArr[pdfNameFromUrlArr.count - 1])
    

    快乐编码:)

    【讨论】:

      【解决方案3】:

      您需要阅读 Apple 的 File and Data Management Guide。它将描述应用程序沙箱中哪些位置可用于在本地保存文件以及如何获取对这些位置的引用。它还有一个阅读和写作部分:)

      享受吧!

      【讨论】:

        【解决方案4】:

        我还建议您查看ASIHTTPRequest,以便轻松下载文件。

        【讨论】:

        • 有没有办法在本地下载文件?这样我以后可以在电子邮件附件中使用它。
        • 我正在使用 ASIHTTPRequest。但不知道下载的文件去哪里了。
        • 你有什么解决方案@Muhammad Jabbar
        【解决方案5】:

        我为它找到了一个 swift 版本:

        let url = "http://example.com/examplePDF.pdf"
        if let pdfData = NSData(contentsOfURL: url) {
            let resourceDocPath = NSHomeDirectory().stringByAppendingString("/Documents/yourPDF.pdf")
            unlink(resourceDocPath)
            pdfData.writeToFile(resourceDocPath, atomically: true)
        }
        

        只要记住保存路径文件,您就可以在需要时获取它。

        【讨论】:

          【解决方案6】:

          使用 Swift 在 Webview 中下载和显示 PDF。

          let request = URLRequest(url:  URL(string: "http://www.msy.com.au/Parts/PARTS.pdf")!)
          let config = URLSessionConfiguration.default
          let session =  URLSession(configuration: config)
          let task = session.dataTask(with: request, completionHandler: {(data, response, error) in
              if error == nil{
                  if let pdfData = data {
                      let pathURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("\(filename).pdf")
                      do {
                          try pdfData.write(to: pathURL, options: .atomic)
                      }catch{
                          print("Error while writting")
                      }
          
                      DispatchQueue.main.async {
                          self.webView.delegate = self
                          self.webView.scalesPageToFit = true
                          self.webView.loadRequest(URLRequest(url: pathURL))
                      }
                  }
              }else{
                  print(error?.localizedDescription ?? "")
              }
          }); task.resume()
          

          【讨论】:

            【解决方案7】:

            使用 Swift 3.0 版语法:

            let url = NSURL(fileURLWithPath: "http://example.com/examplePDF.pdf")
            
                if let pdfData = NSData(contentsOf: url as URL) {
            
                    let resourceDocPath = NSHomeDirectory().appending("/Documents/yourPDF.pdf")
            
                    unlink(resourceDocPath)
            
                    pdfData.write(toFile: resourceDocPath, atomically: true)
            
                }
            

            【讨论】:

              猜你喜欢
              • 2023-03-22
              • 1970-01-01
              • 2021-06-24
              • 1970-01-01
              • 2016-02-19
              • 2012-06-03
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多