How do I use iCloud Drive and ubiquity containers in Swift?

Using iCloud Drive and ubiquity containers in Swift allows you to store and manage user data seamlessly across their devices. By implementing the `NSFileManager` and related APIs, you can keep your app's data synchronized and accessible via iCloud.

Example Code

import Foundation // Function to get the URL for the ubiquity container func getUbiquityURL() -> URL? { if let containerURL = FileManager.default.url(forUbiquityContainerIdentifier: nil) { return containerURL } return nil } // Saving a file to iCloud Drive func saveFileToiCloud() { guard let ubiquityURL = getUbiquityURL() else { print("iCloud is not available") return } let fileURL = ubiquityURL.appendingPathComponent("Documents/myFile.txt") let content = "Hello, iCloud!" do { try content.write(to: fileURL, atomically: true, encoding: .utf8) print("File saved: \(fileURL)") } catch { print("Error saving file: \(error)") } }

iCloud Drive Ubiquity Containers Swift NSFileManager iOS development