File Management in SwiftUI: Read, Write, and Share Files

 

File management is a common need in many iOS apps — whether you’re storing notes, exporting reports, or sharing files with other apps. SwiftUI, in combination with Foundation APIs, allows you to read, write, and share files effectively. In this guide, we’ll explore how to implement file handling in SwiftUI.

✨ What You’ll Learn

  • How to write data to a file in SwiftUI
  • How to read data from a file
  • How to share files using ShareLink or UIActivityViewController

✏️ Writing to a File

Let’s start by writing a simple text file.

func writeTextToFile(text: String, fileName: String) {
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }
let fileURL = dir.appendingPathComponent(fileName)

do {
try text.write(to: fileURL, atomically: true, encoding: .utf8)
print("File written to: \(fileURL)")
} catch {
print("Error writing file: \(error.localizedDescription)")
}
}

Call this function like:

writeTextToFile(text: "Hello, SwiftUI!", fileName: "example.txt")

๐Ÿ“„ Reading from a File

To retrieve data:

func readTextFromFile(fileName: String) -> String? {
guard let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return nil }
let fileURL = dir.appendingPathComponent(fileName)

do {
let content = try String(contentsOf: fileURL, encoding: .utf8)
return content
} catch {
print("Error reading file: \(error.localizedDescription)")
return nil
}
}

๐ŸŒ Sharing a File

SwiftUI provides ShareLink (iOS 16+) for native sharing:

if let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("example.txt") {
ShareLink(item: fileURL) {
Label("Share File", systemImage: "square.and.arrow.up")
}
}

For older iOS versions, use UIActivityViewController:

struct FileShareView: UIViewControllerRepresentable {
var fileURL: URL

func makeUIViewController(context: Context) -> UIActivityViewController {
let controller = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil)
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {}
}

๐Ÿš€ Wrapping It in a SwiftUI App

Here’s a minimal example integrating all these pieces:

struct FileManagerDemoView: View {
@State private var fileContent: String = ""

var body: some View {
VStack(spacing: 20) {
Button("Write to File") {
writeTextToFile(text: "SwiftUI is awesome!", fileName: "demo.txt")
}
Button("Read from File") {
if let content = readTextFromFile(fileName: "demo.txt") {
fileContent = content
}
}
Text("File Content: \(fileContent)")
.padding()
if let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("demo.txt") {
ShareLink(item: fileURL) {
Label("Share File", systemImage: "square.and.arrow.up")
}
}
}
.padding()
}
}

๐Ÿ”ง Use Cases

  • Exporting logs or reports
  • Saving local user notes
  • Sharing generated documents or certificates

๐Ÿš€ Conclusion

With just a few lines of code, you can enable powerful file management in your SwiftUI app. From writing and reading to sharing files, these tools allow you to build robust features that feel native and intuitive.

Comments

Popular posts from this blog

Dependency Injection in iOS with SwiftUI

Using Core ML with SwiftUI: Build an AI-Powered App

CI/CD for iOS Projects with Xcode: A Complete Guide