Skip to content
DeveloperMemos

Saving Documents to the "Files" App in Swift

Swift, iOS, Files App, Document Storage1 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.

Methods to Save Documents

1. Using UIActivityViewController

UIActivityViewController allows users to save documents to the "Files" app among other sharing options.

Example Code

1func saveDocument(documentData: Data, fileName: String) {
2 let activityViewController = UIActivityViewController(activityItems: [fileName, documentData], applicationActivities: nil)
3 present(activityViewController, animated: true, completion: nil)
4}

2. Using UIDocumentInteractionController

UIDocumentInteractionController provides more specific control, including an option to save to "Files."

Example Code

1func showDocumentInteractionController(url: URL) {
2 let docController = UIDocumentInteractionController(url: url)
3 docController.presentOptionsMenu(from: view.bounds, in: view, animated: true)
4}

Creating Documents

Before saving, you might need to create a document, such as a PDF.

Generating a PDF

1func generatePDF() -> Data {
2 let pdfData = NSMutableData()
3 UIGraphicsBeginPDFContextToData(pdfData, CGRect.zero, nil)
4 // Add content to the PDF here
5 UIGraphicsEndPDFContext()
6 return pdfData as Data
7}

Best Practices

  • File Format: Ensure the document is in a format supported by the "Files" app, such as PDF or DOCX.
  • User Permission: Always obtain user permission before saving files, especially if they contain sensitive information.
  • Error Handling: Implement proper error handling to deal with issues like insufficient storage space.