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

8.5k views Asked by At

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?

2

There are 2 answers

4
SATAN On BEST ANSWER

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

1
Edward On

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
        }

    }