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

In visionOS, exporting and importing data via the Files app can be achieved using the FileManager and DocumentPicker APIs. This allows users to interact with files stored in various locations, making it easy to share data between apps and with the system's file manager.

Below is an example of how to present a simple export and import operation using Swift.

// Import needed frameworks import UIKit import MobileCoreServices class FileHandler: UIViewController { func exportToFile() { let fileName = "example.txt" let fileContent = "Hello, world!" let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent(fileName) do { try fileContent.write(to: fileURL, atomically: true, encoding: .utf8) let activityVC = UIActivityViewController(activityItems: [fileURL], applicationActivities: nil) present(activityVC, animated: true, completion: nil) } catch { print("Error exporting file: \(error)") } } func importFromFile() { let documentPicker = UIDocumentPickerViewController(documentTypes: [kUTTypeText as String], in: .import) documentPicker.delegate = self present(documentPicker, animated: true, completion: nil) } } extension FileHandler: UIDocumentPickerDelegate { func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { guard let url = urls.first else { return } do { let importedText = try String(contentsOf: url, encoding: .utf8) print("Imported file content: \(importedText)") } catch { print("Error importing file: \(error)") } } }

Swift visionOS FileManager DocumentPicker Export Import Files app