Please I'm trying to detect if the user is online or offline and I wrote the code below.
Database.database().isPersistenceEnabled = true
let presenceRef = Database.database().reference(withPath: "disconnectmessage");
// Write a string when this client loses connection
presenceRef.onDisconnectSetValue("I disconnected!")
presenceRef.onDisconnectRemoveValue { error, reference in
if let error = error {
print("Could not establish onDisconnect event: \(error)")
}
}
let connectedRef = Database.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
if snapshot.value as? Bool ?? false {
print("Connected")
if Auth.auth().currentUser != nil {
OnlineOfflineService.online(for: (Auth.auth().currentUser?.uid)!, status: true)
}
} else {
print("Not connected")
if Auth.auth().currentUser != nil {
OnlineOfflineService.online(for: (Auth.auth().currentUser?.uid)!, status: false)
}
}
})
and I tried to open the permission.
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
I tried also to use.
func applicationWillTerminate(_ application: UIApplication) {
if Auth.auth().currentUser != nil {
OnlineOfflineService.online(for: (Auth.auth().currentUser?.uid)!, status: false)
}
}
The question is, how can I detect if the user is online or offline? Any suggestions, please??