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_
Rename the download pdf file using swift iOS
try this:
pdfDocument.documentAttributes?["Title"] = "my title attribute"
or
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
Similarly for PDFDocumentAttribute.subjectAttribute
.
The above will set the Title
of your document, and when you save it, the file
name will be whatever file name
you give it.
EDIT-1: saving the pdfDocument
to a file with a chosen file name
.
DispatchQueue.main.async {
guard let unwrappedData = data, error == nil else {
completion(.failure(error ?? Constants.dummyError))
return
}
guard let pdfDocument = PDFDocument(data: unwrappedData) else {
completion(.failure(error ?? Constants.dummyError))
return
}
// set the Title
pdfDocument.documentAttributes?[PDFDocumentAttribute.titleAttribute] = "my title attribute"
do {
// save the document to the given file name ("mydoc.pdf")
let docURL = try FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("mydoc.pdf") // <-- here file name
pdfDocument.write(to: docURL)
print("\n docUrl: \(docURL.absoluteString)\n")
}
catch {
print("Error \(error)")
}
completion(.success(pdfDocument))
}
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 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.
Change name of pdf file programmatically after user selects it from Document Picker
You can do it while you are moving/copying the file to your app's local storage.
Code
/// When you finish picking up a file, you get it's current location in the delegate callback like this.
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
/// Assumption is that you are picking only one file at a time.
guard let url = urls.first else { return }
do {
/// You can copy this move this file to your Documents directory
let documentsDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let newFileName = "custom_name.pdf"
let newFilePath = "\(documentsDirectory)/\(newFileName)"
try FileManager.default.moveItem(at: url, to: URL(fileURLWithPath: newFilePath))
} catch {
/// Handle error
}
}
Related Topics
How to Import Modules Without an Xcode Project in Swift
Swift: How to Hold Any Possible Instance of a Generic Type in a Variable
Subscript of a Struct Doesn't Set Values When Created as an Implicitly Unwrapped Optional
How to Replace Limited Number of Occurrences in String
Xcode Takes Long Time to Print Debug Results
How to Get the Kvc-String from Swift 4 Keypath
Swift Codable - Parse JSON Array Which Can Contain Different Data Type
Swiftui: Update Navigationview After Deletion (Ipad)
How to Deal with Buffered Strings from C in Swift
How to Prevent Eventstore Access Error on First Run
How Does Let X Where X.Hassuffix("Pepper") Work
How to Check If Core Data Is Empty
Xcode Error - Undefined Symbols for Architecture X86_64
Alamofire 5 Upload Encodingcompletion
Make a Type Itself -- Not Its Instances -- Conform to a Protocol
How to Send Data from iPhone to Watchkit in Os2 in Swift
Uiswipegesturerecognizer Doesn't Recognize Swipe Gesture Initiated Outside the View