How to disconnect inactive users in an application chat xcode

107 views Asked by At

I'm trying to find an approach to disconnect an active user for an application chat when the application is in the background for more than 120 second, however the timer seems that it's not working on the background here it's the code

   func sceneDidEnterBackground(_ scene: UIScene) {
        Timer.scheduledTimer(withTimeInterval: 3, repeats: false) { (timer) in
            print("start the logout code")
        }
    }

in the code you can see 3 seconds, because even 3 seconds it's not working. Can you please provide me what is the best approach that i can use so i logout the user and not keep showing him in the online list?

2

There are 2 answers

0
Cod3rMax On BEST ANSWER

I was working on a chat application my self, and I had this problem that took me a long time to figure out a workaround for it.

What I have noticed is that background won't give me a long time to logout the user, so I decided whenver the user or the application enter in:

  1. sceneDidDisconnect

In this case I will call a function that will put the user offline.

if Auth.auth().currentUser != nil {
            print("put offline")
            user.logout()
}
  1. sceneDidBecomeActive

In this case I will call a function that will put the user back online again.

if Auth.auth().currentUser != nil {
            user.offline()
}
  1. applicationWillTerminate

When the application is terminated, I call a function that will put the user Offline then Logout the user and finally Delete the user from database.

I hope this technique will help you.

0
cyberbarker On

The background work is very limited, we cannot do this kind of calculations with a 100% probability that they will be executed. This logic is best left to the backend