I'm backup my database realm file to iCloud by using FileManage
methods. Everything works fine, but there's a trick I want to achieve is:
The file should be backup by iCloud, but NOT shown in iCloud Drive.
For example, GoodNotes 5, we can open the iCloud in settings, verify it's truly backup in iCloud Storage, and the GoodNots 5 App File is not shown in iCloud Drive.
Below is my code that implement iCloud backup, but the App File ama
will be shown in iCloud Drive:
private func retrieveLocalRealmURL() -> URL {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentaryDirectory = urls[0]
let realmURL = documentaryDirectory.appendingPathComponent("ama.realm");
return realmURL
}
private func backupRealmToiCloudDrive() {
let backgroundQueue = DispatchQueue.global(qos: .background)
backgroundQueue.async {
guard
let ubiquityURL = FileManager.default.url(forUbiquityContainerIdentifier: nil)
else {
return
}
let iCloudDriveURL = ubiquityURL.appendingPathComponent("Documents")
let iCloudRealmURL = iCloudDriveURL.appendingPathComponent("ama.realm")
let fileExists = FileManager.default.fileExists(atPath: iCloudDriveURL.path, isDirectory: nil)
func copy() {
let localRealmURL = self.retrieveLocalRealmURL()
do {
try FileManager.default.copyItem(at: localRealmURL, to: iCloudRealmURL)
} catch {
printLog(error.localizedDescription)
}
}
if fileExists {
self.deleteExistedFile(iCloudRealmURL)
copy()
} else {
do {
try FileManager.default.createDirectory(at: iCloudDriveURL, withIntermediateDirectories: true, attributes: nil)
copy()
} catch {
printLog(error.localizedDescription)
}
}
}
}
private func deleteExistedFile(_ url: URL) {
let fileCoordinator = NSFileCoordinator(filePresenter: nil)
fileCoordinator.coordinate(writingItemAt: url, options: .forDeleting, error: nil) { deleteURL in
do {
let fileExists = FileManager.default.fileExists(atPath: deleteURL.path, isDirectory: nil)
if fileExists {
try FileManager.default.removeItem(at: deleteURL)
}
} catch {
printLog(error.localizedDescription)
}
}
}
After many tests, to avoid backup file to iCloud Drive, but in iCloud container, you can just simply remove the 'Documents' path, but using file path directly, like below:
change to:
In this case, the backup file will be stored in iCloud container, but not shown in the user's iCloud Drive.