【问题标题】:Swift 4 Firebase online status updateSwift 4 Firebase 在线状态更新
【发布时间】:2019-03-03 02:26:07
【问题描述】:

我构建了聊天应用程序。我在每个用户表中都有允许检查用户是否在线的字段。我只使用数据库引用来获取 isOnline 状态并在拉动刷新时更新它。我看到当用户打开或折叠应用程序时,应用程序会自动更新在线状态。我怎么能这样做?我需要任何监听器或任何框架可以帮助我升级我的代码))像 ReactiveCocoa/ReactiveSwift 之类的东西......

P.S 对不起字段 isOnline 上的西里尔文字)这意味着在线/离线

【问题讨论】:

标签: swift firebase firebase-realtime-database


【解决方案1】:

当应用启动时,您可以在 AppDelegate 中在线更新用户

在线更新用户

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        FirebaseApp.configure()
        // status parameter indicate user Online
        if Auth.auth().currentUser != nil {
            OnlineOfflineService.online(for: (Auth.auth().currentUser?.uid)!, status: true){ (success) in

                print("User ==>", success)

            }
        }
        return true
    }

离线更新用户

func applicationWillTerminate(_ application: UIApplication) {
        if Auth.auth().currentUser != nil {
            OnlineOfflineService.online(for: (Auth.auth().currentUser?.uid)!, status: false){ (success) in

                print("User ==>", success)
            }
        }
 }

Firebase 在线和离线更新服务

import UIKit
import FirebaseDatabase

struct OnlineOfflineService {
    static func online(for uid: String, status: Bool, success: @escaping (Bool) -> Void) {
        //True == Online, False == Offline
        let onlinesRef = Database.database().reference().child(uid).child("isOnline")
        onlinesRef.setValue(status) {(error, _ ) in

            if let error = error {
                assertionFailure(error.localizedDescription)
                success(false)
            }
            success(true)
        }
    }
}

您还需要注意用户网络连接。如果用户网络连接断开,您只需使用参数调用OnlineOfflineService

【讨论】:

  • 我做了同样的事情......但我遇到的问题是......我需要每次更新(拉刷新)以检查用户是离线还是在线,我想找到方法并更新它无需每次都更新我的视图
  • 好主意。我还将在 AppDelegate 的 applicationWillResignActiveapplicationDidBecomeActive 中添加代码。 @HeorhiiHeints 实时状态,你可以在读取用户时添加一个新的监听器。只需使用observe(.childChanged),这将在每次用户内部的任何数据发生变化时触发。
【解决方案2】:

我知道这是一个较老的问题,但如果您想在用户关闭应用时将在线/离线值设置为 false,请使用 .onDisconnectSetValue()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    FirebaseApp.configure()

    setInactivityObservers()

    return true
}

func setInactivityObservers() {
    guard let user = Auth.auth().currentUser else { return }

    // get user branch of database
    let ref = Database.database().reference()
    let usersRef = ref.child("Users")
    let userRef = usersRef.child(user.uid)

    // set "isOnline" branch to true when app launches
    userRef.child("isOnline").setValue(true)

    // set value to false when user terminates app
    userRef.child("isOnline").onDisconnectSetValue(false)
}

【讨论】:

    【解决方案3】:

    第一

    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")
      } else {
        print("Not connected")
      }
    })
    

    现在可以了吗?

    【讨论】:

    • 和我之前在评论中所说的一样。我每次都有更新数据库的工作示例,但要检查是否在线/离线用户...我每次都需要拉屏幕来刷新我的视图而且我想找到方法,而无需每次都使用“拉动刷新”来更新我的视图
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2018-01-22
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    相关资源
    最近更新 更多