How do I export and import data via Files app on macOS using Swift?

In this guide, we'll explore how to export and import data via the Files app on macOS using Swift. This functionality can be useful for applications that need to save data persistently or load files from the user's system.

Using the FileManager class in Swift, developers can easily access files and directories. Below is an example of implementing file import and export using Swift.

import Cocoa import Foundation // Function to export data func exportData(data: String) { let fileManager = FileManager.default let savePanel = NSSavePanel() savePanel.allowedFileTypes = ["txt"] savePanel.begin { (result) in if result == .OK, let url = savePanel.url { do { try data.write(to: url, atomically: true, encoding: .utf8) print("Data exported successfully!") } catch { print("Error exporting data: \(error)") } } } } // Function to import data func importData() { let openPanel = NSOpenPanel() openPanel.allowedFileTypes = ["txt"] openPanel.begin { (result) in if result == .OK, let url = openPanel.url { do { let importedData = try String(contentsOf: url, encoding: .utf8) print("Data imported successfully: \(importedData)") } catch { print("Error importing data: \(error)") } } } }

Swift macOS Files app export data import data FileManager