How do I get a server timestamp from Firebase's iOS API?

后端 未结 4 669
迷失自我
迷失自我 2020-12-25 15:23

I have an iOS app that uses Firebase and currently has a few dictionaries with keys that are NSDate objects. The obvious issue with this is that NSDate draws from the devic

4条回答
  •  情话喂你
    2020-12-25 15:42

    Update: In Firebase 3.0 + Swift, you can use FIRServerValue.timestamp(). In Objective-C this is [FIRServerValue timestamp].

    In Swift, you can now use FirebaseServerValue.timestamp() with Firebase 2.0.3+ (before 3.0).

    The equivalent for Firebase.ServerValue.TIMESTAMP in iOS is kFirebaseServerValueTimestamp. Right now, this only works for Objective-C and not Swift.

    In Swift, you can create your own global timestamp with

    let kFirebaseServerValueTimestamp = [".sv":"timestamp"]
    

    and then you'll be able to use kFirebaseServerValueTimestamp in the same way.

    But you can only use this as the value or priority of a node. You won't be able to set it as the key name (although, I don't believe you could in the Web API either).

    In general, calling allKeys on a dictionary does not guarantee order. But if you're using childByAutoID at a node, you can get back the right order by ordering the NSArray returned by allKeys lexicographically. Something like this would work:

    [ref observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
        NSDictionary *value = snapshot.value;
        NSLog(@"Unsorted allKeys: %@", value.allKeys);
        NSArray *sortedAllKeys = [value.allKeys sortedArrayUsingSelector:@selector(compare:)];
        NSLog(@"Sorted allKeys: %@", sortedArray);
    }];
    

    This is similar to sorting an NSArray alphabetically, but when sorting the auto-generated IDs, you do not want localized or case insensitive sort, so you use compare: instead of localizedCaseInsensitiveCompare:

提交回复
热议问题