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

Exporting and importing data via the Files app on watchOS can enhance your app's capabilities by allowing users to easily manage their data. This guide will cover how to use the FileManager API to handle files and data within your watchOS application.

Exporting Data

To export data, you will first want to create a file in a directory accessible to the Files app. Below is an example of how to write data to a file:

let fileManager = FileManager.default let documentsDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first! let fileURL = documentsDirectory.appendingPathComponent("example.txt") let textToSave = "Hello, watchOS!" do { try textToSave.write(to: fileURL, atomically: true, encoding: .utf8) print("File exported successfully to \(fileURL.path)") } catch { print("Error writing file: \(error)") }

Importing Data

To import data, you will need to read a file from the shared directory. Here's how you can read a file's content:

let fileURL = documentsDirectory.appendingPathComponent("example.txt") do { let importedText = try String(contentsOf: fileURL, encoding: .utf8) print("File imported successfully: \(importedText)") } catch { print("Error reading file: \(error)") }

By utilizing the FileManager, you can manage file operations effectively on watchOS, providing your users with seamless data handling.


watchOS FileManager export data import data Files app Swift example watchOS development