Search code examples
iosswiftrealmappdelegateterminate

Removing Realm Data in the applicationWillTerminate


I have the following case, I delete the non-actual data from Realm when the application is thrown from the device's memory. I have a special FriendRealmManager class, this class contains the function clearCache, it deletes users (which are not friends at the moment). When I call this manager in the applicationWillTerminate function, after I return to the application, I see that this function did not work, because there are models of users who are no longer friends. I tried to move the code of the clearCache function into the applicationWillTerminate and this works. Tell me please, is it possible to do something like that to work functions from different managers in applicationWillTerminate?

I tried both the normal function and the static one.

It doesn't work

func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        FriendRealmManager.clearCache()
    }

class FriendRealmManager {

    static func clearCache() {
        DispatchQueue.main.async {
            do {
                let realm = try Realm()
                try realm.write {
              let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
                }
            } catch {
                debugPrint(error.localizedDescription)
            }
        }
    }
}

It works

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    do {
        let realm = try! Realm()
        try realm.write {
       let nonFriendUsers = realm.objects(RealmUser.self).filter("isFriend == %@ AND isMain == %@", false, false)
                realm.delete(nonFriendUsers)
        }
    } catch {
        debugPrint(error.localizedDescription)
    }
}

Solution

  • The most probable reason for your function not working is that you call it as an asynchronous function and the system terminates your app before your function could execute. Looking at the official documentation of applicationWillTerminate, it states that

    Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

    Hence, I would suggest deleting the DispatchQueue.main.async part from your function and just running your deletion synchronously.