-1

I am working on a chatting application, where i have to maintain user "offline" or "online" status.I want the user status will be offline when user enters in background and also if user will kill the app.In my app in the background case it is working fine. but it is not working fine when i kill the app.My code is: -

func applicationDidEnterBackground(_ application: UIApplication) {
    if let uid: Int = UserDefaults.standard.value(forKey: "User_Id") as? Int{
          reference(.User).whereField(kREGISTERUSEID, isEqualTo: "\(uid)").getDocuments { (snapshot, err) in
              if let err = err {
              }
              else {
                  let document = snapshot!.documents.first
                  document!.reference.updateData([
                      kISONLINE: false
                  ])
              }
          }
    }
}
 func applicationDidBecomeActive(_ application: UIApplication) {
    if let uid: Int = UserDefaults.standard.value(forKey: "User_Id") as? Int{
            reference(.User).whereField(kREGISTERUSEID, isEqualTo: "\(uid)").getDocuments { (snapshot, err) in
                if let err = err {
                }
                else {
                    let document = snapshot!.documents.first
                    document!.reference.updateData([
                        kISONLINE: true
                    ])
                }
            }
    }

}

func applicationWillTerminate(_ application: UIApplication) {
    if let uid: Int = UserDefaults.standard.value(forKey: "User_Id") as? Int{
                reference(.User).whereField(kREGISTERUSEID, isEqualTo: "\(uid)").getDocuments { (snapshot, err) in
                    if let err = err {
                    }
                    else {
                        let document = snapshot!.documents.first
                        document!.reference.updateData([
                            kISONLINE: false
                        ])
                    }
                }
          }

}

I am using firebase here.Also i want to make user offline if user will not go to the chat screen or will not send message to any one (like whatsapp) for 20 seconds .

Please help me to implement it. Thanks

Asperi
  • 228,894
  • 20
  • 464
  • 690
  • You should not called any api's in application terminate method, because in that app don't have much time to execute api request and response – Akshay Savaliya Dec 31 '19 at 07:27

1 Answers1

0

Your api or firebase call must be performed on the background mode. Go the link you will find how to crate a background task.

Can I make an api call when the user terminates the app?

Md Raqeeb
  • 21
  • 7