Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a firebase server timestamp using the iOS SDK in Swift project

In the "Offline Capabilities" section of the iOS guide it mentions kFirebaseServerValueTimestamp, which doesn't seem to work in a Swift project (auto complete doesn't prompt it).

I tried [".sv": "timestamp"] as the Swift example did. But it complains that this can not be set with other values and has to be the only value for at the given path.

I tried:

ref.childByAutoId().setValue(["text": "foobar", ".sv": "timestamp"], withCompletionBlock: {...} 

And it gave me the error that ".sv" can't be saved with other value.

What I wanted to do is to save the createdAt timestamp along with other values for the object. And I'd prefer to use the server time to avoid client clock skew.

How can I do that?

like image 839
Quan Ding Avatar asked Jun 17 '15 05:06

Quan Ding


People also ask

How do I connect firebase to iOS app?

Go to the Firebase console. In the center of the project overview page, click the iOS+ icon to launch the setup workflow. If you've already added an app to your Firebase project, click Add app to display the platform options. Enter your app's bundle ID in the bundle ID field.

What is firebase timestamp?

A Timestamp represents a point in time independent of any time zone or calendar, represented as seconds and fractions of seconds at nanosecond resolution in UTC Epoch time. It is encoded using the Proleptic Gregorian Calendar which extends the Gregorian calendar backwards to year one.

How do I find my Firebase server date?

To reach the timestamp of firebase server on client, you first need to write the value to the server then read the value. firebase. database(). ref('currentTime/').


2 Answers

Add the ".sv":"timestamp" between brackets [ ] when you add it to your Firebase entry.

eg:

let objectToSave: Dictionary <String: AnyObject> = ["date": [".sv": "timestamp"], "key1": "value1", "key2": 1234.....] 

Code screenshot

It should be written to your Firebase as:

date: 1463329843759

Firebase screenshot

like image 160
SATAN Avatar answered Oct 27 '22 17:10

SATAN


As of Firebase 4.0 you can use ServerValue.timestamp()

for example:

    let ref = Database.database().reference().child("userExample")
    let values = ["firstName": "Joe", "lastName": "Bloggs", "timestamp": ServerValue.timestamp()] as [String : Any]

    ref.updateChildValues(values) { (err, ref) in

        if let err = err {
            print("failed to upload user data", err)
            return
        }

    }
like image 20
Edward Avatar answered Oct 27 '22 18:10

Edward