swift - 如何在不重新加载控制器的情况下更新用户在线状态?
问题描述
因此,我制作了一个可用的聊天应用程序,其中后端是 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)
}
}
}
}
解决方案
这成功了旧代码中存在一些问题
func updateUserOnlineStatus() {
print("User update online status")
if !isGroup! {
var withUser = withUsers.first!
withUserUpdateListener = reference(.User).document(withUser.objectId).addSnapshotListener { (snapshot, error) in
if error != nil {
print("error")
}
print("update user status")
let withUser = FUser(_dictionary: snapshot!.data()! as NSDictionary)
if withUser.isOnline == "online" {
self.navigationController?.navigationBar.barTintColor = UIColor.flatGreen()
}else{
self.navigationController?.navigationBar.barTintColor = UIColor.flatBlue()
}
}
}
}
推荐阅读
- go - 用 Golang 简化字符串中的变量替换
- gradle - 使用自定义 gradle 插件的 Gradle 复合构建在 IntelliJ 中失败:“找不到参数的方法 api()”
- javascript - `Proxy` 将 `this[toString]` 与 `this[Symbol.toStringTag]` 混淆
- pytorch - 在 pytorch 中使用 expand_dims
- c# - Xamarin Firebase 发送电子邮件验证
- opengl - 为什么在 OpenGL 中使用 glm::LookAt?
- php - PHP 语句中的 SQL 变量
- mysql - mysql导入csv数据错误
- sql - 从 varchar 到 datetime 的转换导致值超出范围
- typescript - 如何检查数组中每个对象中的布尔值是否为假?