【发布时间】:2019-03-09 23:34:51
【问题描述】:
所以我制作了一个可用的聊天应用程序,其中后端是 Firestore(我知道有 Firebase。)我还有一个文档,其中用户在线离线状态是记录器。
当用户登录“isOnline”节点时,该值会更改为 true 或“online”,而当应用进入后台时,该值会更改为“offline”。
唯一的问题是我必须重新加载 viewController 才能进行更改。有什么办法可以实时更新用户状态
AppDelegate:-
在 ApplicationDidBecomeActive 中
if User.currentUser() != nil {
updateCurrentUserInFirestore(withValues: [kISONLINE : "online"]) { (success) in
}
}
在 ApplicationDidEnterBackground 中
if User.currentUser() != nil {
updateCurrentUserInFirestore(withValues: [kISONLINE : "offline"]) { (success) in
}
}
比chatViewController中导航栏的设置如下
userstatus func
if withUser.isOnline == "online" {
navigationController?.navigationBar.barTintColor = UIColor.flatGreen()
}else{
navigationController?.navigationBar.barTintColor = UIColor.flatBlue()
}
下面是检查状态变化的功能
func updateUserOnlineStatus() {
if !isGroup! {
var withUser = withUsers.first!
withUserUpdateListener = reference(.User).document(withUser.isOnline).addSnapshotListener { (snapshot, error) in
guard let snapshot = snapshot else { return }
if snapshot.exists {
print(snapshot)
let withUser = User(_dictionary: snapshot.data()! as NSDictionary)
self.setUIForSingleChat(withUser: withUser)
}
}
}
}
【问题讨论】:
-
好吧,你可以创建一些可观察的类来通知观察对象的状态变化。然后在您的 viewController 中,您将自己添加为观察者,一旦用户登录或退出,您就会收到通知。或者,您可以使用
NSNotification和NSNotificationCenter通知您的 viewController 发生了变化。
标签: swift firebase-realtime-database google-cloud-firestore user-presence