简体   繁体   中英

How to return a Firebase timestamp from a cloud function

I'm calling a Firebase Cloud Function from an iOS app. It works as expected but how do I return a value from my cloud function that's read as a FIRTimestampValue from iOS?

Firebase does this for Firestore documents. If I get a Firestore document with a timestamp value, it's returned as a dictionary object just like a cloud function result but the timestamp values are encoded as FIRTimestamp objects.

I would like to know if I need to do any special encoding on the server side to make this happen or if there is some other Firebase function in the iOS SDK to parse the result from the cloud function so that timestamp values will be encoded as FIRTimestamp objects.

Here is an example.

Javascript (Cloud Function):

exports.myFunction = functions.https.onCall((data, context) => {
    var dateText = "2020-10-29T21:17:51Z";
    return {"myDate": Date.parse(dateText)}
});

iOS (App):

FIRFunctions *functions = [FIRFunctions functions];
FIRHTTPSCallable *function = [functions HTTPSCallableWithName:@"myFunction"];
[function callWithObject:@{} completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
    NSDictionary *data = result.data;

    // How do I get this to be a FIRTimestamp?
    FIRTimestamp *timestamp = data["myDate"]; 
}];

Callable functions only return raw JSON objects to the caller. JSON can only contain objects, arrays, strings, numbers, booleans, or null. It's up to the caller to translate whatever is in the resulting object to the native data types it wants to use. You won't be able to get a FIRTimestampValue directly from the function.

Instead, your function should convert the timestamp to some normalized form (for example, milliseconds since epoch), then convert that number into a FIRTimestampValue in the client app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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