Saving PDF Files with Swift in iOS and display them
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)
_x0013_
How to download a Pdf file in swift and find in file manager
Configure your app so that its files appear in the Files app by adding below lines to your Info.plist
file.
<key>UIFileSharingEnabled</key>
<true/>
<key>LSSupportsOpeningDocumentsInPlace</key>
<true/>
OR
Just like below using Xcode
Note: Remember that you must be running iOS 11 or above.
Download PDF and save to the Files in iPhone, not to the app data, Swift]
Here's how to download any files and save to Photos(if image file) or Files (if pdf)
let urlString = "your file url"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
// Create destination URL
let documentsUrl:URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Create URL to the source file you want to download
let fileURL = URL(string: urlString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
// Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
do {
//Show UIActivityViewController to save the downloaded file
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
print("error: \(err)")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
}
}
task.resume()
Download PDF file and save in document directory
You need to move the file to your custom location after the download. Implement URLSessionDownloadDelegate
and you will receive the location of your downloaded file.
Delegate method:
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
Code to move the file:
do {
let documentsURL = try
FileManager.default.url(for: .documentDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: false)
let savedURL = documentsURL.appendingPathComponent("yourCustomName.pdf")
try FileManager.default.moveItem(at: location, to: savedURL)
} catch {
print ("file error: \(error)")
}
To learn more refer to this repo.
Swift - Automatically save pdf file to Files app On My iPhone
Example of download any pdf file and automatically save inside files folder of iPhone.
let urlString = "https://www.tutorialspoint.com/swift/swift_tutorial.pdf"
let url = URL(string: urlString)
let fileName = String((url!.lastPathComponent)) as NSString
//Mark: Create destination URL
let documentsUrl:URL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL?)!
let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
//Mark: Create URL to the source file you want to download
let fileURL = URL(string: urlString)
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig)
let request = URLRequest(url:fileURL!)
let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
if let tempLocalUrl = tempLocalUrl, error == nil {
//Mark: Success
if let statusCode = (response as? HTTPURLResponse)?.statusCode {
print("Successfully downloaded. Status code: \(statusCode)")
}
do {
try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
do {
//Mark: Show UIActivityViewController to save the downloaded file
let contents = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
for indexx in 0..<contents.count {
if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
}
}
catch (let err) {
print("error: \(err)")
}
} catch (let writeError) {
print("Error creating a file \(destinationFileUrl) : \(writeError)")
}
} else {
print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
}
}
task.resume()
How to show PDF from NSData in Swift - how to save PDF to documents folder Swift - how to display PDF from saved NSData via WebView in Swift
First of all, that NSData IS your PDF, no need to convert to another data type or use a library to manipulate it at the moment.
For now, simply save the NSData to your documents directory on iOS, which is not a managed persistent store like CoreData or Realm, nor is it UserDefaults. It's a folder with stuff in it.
Save to Documents Folder:
let data = //the stuff from your web request or other method of getting pdf
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
let filePath = "\(documentsPath)/myCoolPDF.pdf"
data.writeToFile(filePath, atomically: true)
Now verify that the file is there and open it on your mac. This is to make sure you've saved an actual PDF and not anything else. This is a two step process. First find out where on earth the file went by printing the location of the documents folder from the iOS simulator:
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
print(documentsDirectory)
Now copy that really long filepath and cd [paste location]
in terminal to go there, then open myCoolPDF.pdf
to open it in Preview! It's magical times!
Now that you have verified that you're dealing with an actual PDF it's time to display that in a WebView since it's quite simple unless you've got your own way of doing so.
Note that you still have to make it so the webview shows up, drag one onto your viewController in a storyboard and make an IBOutlet for it.
let url = NSURL(fileURLWithPath: filePath)
let webView = UIWebView()
webView.loadRequest(NSURLRequest(URL: url))
Obviously this is a quick way to make sure you get the basics going, you don't want to force unwrap unsafely using !
.
Cannot add image and save to pdf file using PDFKit
I have to also draw that image on PDFPage
to make them appear in the saved pdf file
final private class ImagePDFPage: PDFPage {
/// A flag indicates whether to draw image on a page
///
/// - Note: Set this to `true` before write pdf to file otherwise the image will not be appeared in pdf file
var saveImageToPDF: Bool = false
private var imageAnnotation: EkoPDFImageAnnotation? = nil
func addImageAnnotation(_ annotation: EkoPDFImageAnnotation) {
imageAnnotation = annotation
addAnnotation(annotation)
}
func removeImageAnnotation() {
guard let imageAnnotation = imageAnnotation else { return }
self.imageAnnotation = nil
removeAnnotation(imageAnnotation)
}
override func draw(with box: PDFDisplayBox, to context: CGContext) {
super.draw(with: box, to: context)
guard saveImageToPDF,
let annotation = imageAnnotation,
let cgImage = annotation.image?.cgImage else { return }
context.draw(cgImage, in: annotation.bounds)
}
}
and update PDFDocument.delegate
to tell to use ImagePDFPage
as a class for pdf page
extension PDFEditorViewController: PDFDocumentDelegate {
func classForPage() -> AnyClass {
return ImagePDFPage.self
}
}
The result
Related Topics
How to Make a Call Which Begin with * in Iphone
Please Clear Some Confusions Regarding Uiviewcontroller
Facebook iOS Sdk - Get Friends List
Accessing Core Data SQL Database in iOS 8 Extension (Sharing Data Between App and Widget Extension)
Invalid Update: Invalid Number of Items on Uicollectionview
How to Customize the Page Indicator in Uipageviewcontroller
How to Track User Location in Background
How to Properly Change My Status Bar Style in Swift 2/ iOS 9
Filenames Are Used to Distinguish Private Declarations of the Same Name' Error
Storyboard Uiviewcontroller, 'Custom Class' Not Showing in Drop Down
@State Var Not Updated as Expected in Lazyvgrid
Alamofire: Sending JSON as Request Parameter
Cllocationmanager and Accuracy Issues - Any Experiences
How to Detect Taps on Mkpolylines/Overlays Like Maps.App
Facebook Share Content Only Shares Url in iOS 9
Uiscrollview Adjusts Contentoffset When Contentsize Changes