Search code examples
iosswiftrealm

Reset schema for all Realms in Realm Cloud


Is there any way I can completely nuke everything from my Realm Cloud, including existing schema definitions?


Solution

  • There is a way to delete the Realms from the Realm Object Server.

    Here's information I collected on a Realm Forums Post

    Here's a link to the official docs.

    This is super important though. The docs I am linking are for Docs 3.0. Self-hosting appears to be going away so the 3.16 Docs no longer include this information.

    There are two steps

    Remove server files
    Remove all local files
    

    These both have to be done or else Realm will try to re-sync itself and your data will never go away.

    The first function deletes a Realm Cloud instance and if successful, deletes the local realm files.

    //
    //MARK: - delete database
    //
    func handleDeleteEverything() {
        let realm = RealmService //Singleton that returns my realm cloud
        try! realm.write {
            realm.deleteAll()
        }
    
        guard let currentUser = SyncUser.current else {return}
        let adminToken = currentUser.refreshToken!
    
        let urlString = "https://your_realm.cloud.realm.io" //from RealmStudio upper right corner
        let endPoint = "\(urlString)/realms/files/realm_to_delete"
        let url = URL(string: endPoint)
        var request = URLRequest(url: url!)
        request.httpMethod = "DELETE"
        request.addValue(adminToken, forHTTPHeaderField: "Authorization")
    
        let task = URLSession.shared.dataTask(with: request) { data, response, error in
            if let err = error {
                print("err = \(err.localizedDescription)")
                return
            }
    
            print("Realm has been deleted")
            self.deleteLocalRealmFiles() //remove local files
        }
        task.resume()
    }
    

    and then the function to remove the local files. This function is a bit different than what appears on the Realm Forums post with the addition of this function in Realm 4.2

    try Realm.deleteFiles(for: config)
    

    and the function that calls it

    func deleteLocalRealmFiles() {
    
        do {
            let config = Realm.Configuration.defaultConfiguration
            let isSuccess = try Realm.deleteFiles(for: config)
            if isSuccess == true {
                print("local files were located and deleted")
            } else {
                print("no local files were deleted, files were not found")
            }
    
        } catch let error as NSError {
            print(error.localizedDescription)
        }
    }