26

I am able to successfully view a PDF from a website. I want to be able to download that PDF to the device, then access that file locally.

When the app is opened, it will check the online PDF's date. If it is newer than the locally-stored PDF, the app will download the new one, otherwise it opens the locally-stored PDF.

The code I am currently using:

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

How am I able to achieve this?

BryanH
  • 5,826
  • 3
  • 34
  • 47
Zac Altman
  • 1,215
  • 4
  • 25
  • 37

7 Answers7

50

I have found one method which I tried myself:

// 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];

This will store your PDF locally and load it into your UIWebView.

halfer
  • 19,824
  • 17
  • 99
  • 186
RVN
  • 4,157
  • 5
  • 32
  • 35
  • I am using this url ** http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UIWebView_Class/UIWebView_Class.pdf**. what should i pass here in stringByAppendingPathComponent:myPDF.pdf??? Which pdf name should i pass? Please help me. – Manthan Feb 18 '14 at 13:52
  • sorry for a late reply, you need to pass the name of the PDF you want to store is as, along with the extension ".pdf" as a string. – RVN Feb 27 '14 at 16:23
  • Yes, I got that. Thanks so much for your reply and help. +1 for it. – Manthan Feb 28 '14 at 10:15
  • How do I retrieve it?? – Seb OH Apr 10 '14 at 05:22
  • @RVN i have used this code and saved the PDF.. But wen i open adobe reader app in my iPad, it shows nothing. Y am i not getting any pdf there? Where does the pdf got saved? – Mano May 27 '14 at 11:55
  • @manoj : The file is saved locally in your app, it is not accessible outside your app (Sandboxing), you can use UIActivityController to open the PDF in the adobe reader. – RVN Jun 12 '14 at 11:43
  • @seenu : you need to use NSURLConnection and you will know the total size and calculate the percent each time you receive data. – RVN Oct 16 '14 at 05:56
  • what If I want to access this file outside my App for later use.? @RVN – Jabbar Sep 09 '15 at 11:11
3

In 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)

If you want to save the Pdf's in a particular folder/directory inside Main Document Directory

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])

Happy Coding :)

Ariven Nadar
  • 1,278
  • 13
  • 13
0

You need to read the File and Data Management Guide from Apple. It will describe which locations are available in the application sandbox for saving files locally and how to get a reference to those locations. It also has a section for reading and writing :)

Enjoy!

willcodejavaforfood
  • 43,223
  • 17
  • 81
  • 111
0

I'd also recommend taking a look at ASIHTTPRequest for easy file downloading.

matkins
  • 1,991
  • 1
  • 16
  • 22
0

I found a swift version for it:

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)
}

Just remember to save the path file and you'll be able to fetch it whenever you need it.

Fernando Mata
  • 482
  • 1
  • 10
  • 22
0

Downloading and displaying PDF in Webview using Swift.

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()
BIJU C
  • 21
  • 5
-1

With Swift version 3.0 syntax:

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)

    }
peacetype
  • 1,928
  • 3
  • 29
  • 49
sandy
  • 3
  • 1