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)")
}
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?