— Swift, iOS, Files App, Document Storage — 1 min read
Saving documents to the "Files" app in iOS using Swift is a common requirement for many apps. This article explores how to save PDFs and other documents to the "Files" app, providing users with a familiar and convenient way to access these files.
UIActivityViewController
allows users to save documents to the "Files" app among other sharing options.
1func saveDocument(documentData: Data, fileName: String) {2 let activityViewController = UIActivityViewController(activityItems: [fileName, documentData], applicationActivities: nil)3 present(activityViewController, animated: true, completion: nil)4}
UIDocumentInteractionController
provides more specific control, including an option to save to "Files."
1func showDocumentInteractionController(url: URL) {2 let docController = UIDocumentInteractionController(url: url)3 docController.presentOptionsMenu(from: view.bounds, in: view, animated: true)4}
Before saving, you might need to create a document, such as a PDF.
1func generatePDF() -> Data {2 let pdfData = NSMutableData()3 UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)4 // Add content to the PDF here5 UIGraphicsEndPDFContext()6 return pdfData as Data7}