简体   繁体   English

如何在iOS和Swift中使用带查询启动属性的Firebase服务器时间戳和queryStartingAtValue来跟踪用户的当前操作

[英]How do I use a firebase server timestamp, with queryStartingAtValue, to track a user's current actions, for a firebase listener in iOS & Swift

I am developing an iOS app in Swift which has a like feature which is the same concept as liking a Facebook post, a Twitter Tweet etc. 我正在Swift中开发一个iOS应用程序,该应用程序具有类似功能,与喜欢Facebook帖子,Twitter Tweet等的概念相同。

I want to create a listener that only listens to the user liking posts with a timestamp that starts from now. 我想创建一个监听器,该监听器仅监听从现在开始带有时间戳的用户喜欢的帖子。 ie once they open the app. 即一旦他们打开应用程序。 I wanted to use a firebase server timestamp value to get the current timestamp 我想使用Firebase服务器时间戳值获取当前时间戳

I have the following structure in my database 我的数据库中具有以下结构

    "userLikes": {
        "$uid":{
            "$messageId": {
                "timestamp": 1212121212121 // timestamp created using fb server
            }
        }
    }

This was my attempted solution but it doesn't work and the problem I have is to do with -> FIRServerValue.timestamp() 这是我尝试的解决方案,但是它不起作用,而我遇到的问题与-> FIRServerValue.timestamp()有关

    let queryRef = ref.child("userLikes").child(uid).queryOrdered(byChild: "timestamp").queryStarting(atValue: FIRServerValue.timestamp())
    queryRef.observe(.childAdded, with: { (snapshot) in

        let utterId = snapshot.key
        self.newsFeedModel.uttersInfo[utterId]?[Constants.UttersInfoKeys.isLikedByCurrentUser] = true as AnyObject

        DispatchQueue.main.async {
            self.collectionView.reloadData()
        }

    }, withCancel: nil)

Any ideas how I Can implement this? 有什么想法可以实现吗? Perhaps I should just use NSDate to get the current time for comparison but thought that using a firebase server timestamp would be the optimum way for comparison purposes. 也许我应该只使用NSDate来获取当前时间进行比较,但认为使用Firebase服务器时间戳将是进行比较的最佳方法。

You can estimate the ServerTime by taking the local time and correcting for the clock-skew and latency. 您可以通过获取本地时间并校正时钟偏斜和延迟来估计ServerTime。 The Firebase documentation has a section on Clock Skew . Firebase文档的“时钟偏斜”部分

Clock Skew 时钟偏斜

While firebase.database.ServerValue.TIMESTAMP is much more accurate, and preferable for most read/write ops, it can occasionally be useful to estimate the clients clock skew with respect to the Firebase Realtime Database's servers. 虽然firebase.database.ServerValue.TIMESTAMP更为准确,并且对于大多数读/写操作而言更为可取,但偶尔估计相对于Firebase Realtime Database服务器的客户端时钟偏差可能很有用。 We can attach a callback to the location /.info/serverTimeOffset to obtain the value, in milliseconds, that Firebase Realtime Database clients will add to the local reported time (epoch time in milliseconds) to estimate the server time. 我们可以在位置/.info/serverTimeOffset上附加一个回调,以获取以毫秒为单位的值,该值是Firebase Realtime Database客户端将添加到本地报告时间(以毫秒为单位的纪元时间)以估计服务器时间的值。 Note that this offset's accuracy can be affected by networking latency, and so is useful primarily for discovering large (> 1 second) discrepancies in clock time. 请注意,此偏移量的准确性可能会受到网络延迟的影响,因此主要用于发现时钟时间中的较大差异(> 1秒)。

 let offsetRef = FIRDatabase.database().referenceWithPath(".info/serverTimeOffset") offsetRef.observeEventType(.Value, withBlock: { snapshot in if let offset = snapshot.value as? Double { let estimatedServerTimeMs = NSDate().timeIntervalSince1970 * 1000.0 + offset } }) 

This will likely work better than purely using a client-side timestamp, since that is likely to be different between clients. 这可能比纯粹使用客户端时间戳更好,因为客户端之间的时间戳可能有所不同。

Update for Swift 3/4: Swift 3/4的更新:

public func getCurrentTime(completionHandler:@escaping (Double) -> ()){
    Database.database().reference(withPath: ".info/serverTimeOffset").observeSingleEvent(of: .value) { (snapshot) in
        if let time = snapshot.value as? Double{
           completionHandler(Date().timeIntervalSince1970 + time)
        }else{
            completionHandler(0)

        }
    }
}

Usage: 用法:

    getCurrentTime(){ (date) in
        print(date)
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM