使用Swift和Firebase了解用户是否在线

时间:2018-03-20 15:23:52

标签: ios swift firebase swift3

我目前正在将信使编码到我的socialApp中。 我想知道我正在与之交谈的人是否在线。

首先,它可以让我显示用户是否在线:

enter image description here

然后,我可以允许我发送推送通知(因为用户在聊天中)。

我想在数据库中创建一个简单的子项(类似于:

isOnline
|_User1
   |__User2: true

现在,我的问题是我不知道如何切换价值。

  • 如果用户访问该页面 - >设置为true(OK)
  • 如果用户clic on back按钮 - >删除值(确定)
  • 当用户离开应用时(即使在后台) - >删除值(不正常)

处理的好方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以在 AppDelegate 中使用 applicationWillResignActive applicationDidBecomeActive 来通知用户是否在线:

func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        // user is offline 
        let ref = Database.database().reference.child("isOnline").child(user)
        ref.setValue(false) // NO
    }

func applicationDidBecomeActive(_ application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        let ref = Database.database().reference.child("isOnline").child(user)
        ref.setValue(true) // YES
}