Swift 4 Firebase在线状态更新

时间:2018-05-07 11:49:29

标签: swift firebase firebase-realtime-database

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

P.S抱歉字段 isOnline 上的西里尔文字,这意味着在线/离线 enter image description here

3 个答案:

答案 0 :(得分:2)

当应用程序启动时,您可以在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

答案 1 :(得分:0)

第一

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")
  }
})

现在好吗?

答案 2 :(得分:0)

我知道这是一个比较老的问题,但是如果您要在用户关闭应用程序时将在线/离线值设置为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)
}