Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving PDF Files with Swift in iOS and display them

I want to build an app which also includes the possibility to show and save PDFs inside the app and display them (as a FileSystem) within a tableview and open them when I tap on one PDF.

Here are my important questions for that:

1. How do I save a PDF local on my app ( for example if the user can enter a url) and where exactly will it save it ?

2. When saved, how can I show all the local storaged files within a tableview to open them?

like image 971
MkaysWork Avatar asked Apr 06 '15 21:04

MkaysWork


2 Answers

Since several people requested this, here is the equivalent to the first answer in Swift:

//The URL to Save let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf") //Create a URL request let urlRequest = NSURLRequest(URL: yourURL!) //get the data let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)  //Get the local docs directory and append your local filename. var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL  docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")  //Lastly, write your file to the disk. theData?.writeToURL(docURL!, atomically: true) 

Also, since this code uses a synchronous network request, I highly recommend dispatching it to a background queue:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in     //The URL to Save     let yourURL = NSURL(string: "http://somewebsite.com/somefile.pdf")     //Create a URL request     let urlRequest = NSURLRequest(URL: yourURL!)     //get the data     let theData = NSURLConnection.sendSynchronousRequest(urlRequest, returningResponse: nil, error: nil)      //Get the local docs directory and append your local filename.     var docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)).last as? NSURL      docURL = docURL?.URLByAppendingPathComponent( "myFileName.pdf")      //Lastly, write your file to the disk.     theData?.writeToURL(docURL!, atomically: true) }) 

And the answer to second question in Swift:

//Getting a list of the docs directory let docURL = (NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last) as? NSURL  //put the contents in an array. var contents = (NSFileManager.defaultManager().contentsOfDirectoryAtURL(docURL!, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil)) //print the file listing to the console println(contents) 

like image 71
Satre Avatar answered Sep 20 '22 23:09

Satre


Swift 4.1

 func savePdf(urlString:String, fileName:String) {         DispatchQueue.main.async {             let url = URL(string: urlString)             let pdfData = try? Data.init(contentsOf: url!)             let resourceDocPath = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last! as URL             let pdfNameFromUrl = "YourAppName-\(fileName).pdf"             let actualPath = resourceDocPath.appendingPathComponent(pdfNameFromUrl)             do {                 try pdfData?.write(to: actualPath, options: .atomic)                 print("pdf successfully saved!")             } catch {                 print("Pdf could not be saved")             }         }     }      func showSavedPdf(url:String, fileName:String) {         if #available(iOS 10.0, *) {             do {                 let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)                 let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)                 for url in contents {                     if url.description.contains("\(fileName).pdf") {                        // its your file! do what you want with it!                  }             }         } catch {             print("could not locate pdf file !!!!!!!")         }     } }  // check to avoid saving a file multiple times func pdfFileAlreadySaved(url:String, fileName:String)-> Bool {     var status = false     if #available(iOS 10.0, *) {         do {             let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)             let contents = try FileManager.default.contentsOfDirectory(at: docURL, includingPropertiesForKeys: [.fileResourceTypeKey], options: .skipsHiddenFiles)             for url in contents {                 if url.description.contains("YourAppName-\(fileName).pdf") {                     status = true                 }             }         } catch {             print("could not locate pdf file !!!!!!!")         }     }     return status } 
like image 25
Ahmadreza Avatar answered Sep 20 '22 23:09

Ahmadreza