Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if user is online when using Firebase iOS SDK

Tags:

ios

firebase

Before sending a message (i.e. calling setValue on a Firebase object), is there a recommended way to determine if the user is online or offline?

For example:

[firebase setValue:someValue withCompletionBlock:^(NSError *error, Firebase *ref) {

    // This block is ONLY executed if the write actually completes. But what if the user was offline when this was attempted?
    // It would be nicer if the block is *always* executed, and error tells us if the write failed due to network issues.

}];

We need this in our iOS app because the user could lose connectivity if they went into a tunnel for instance. If Firebase doesn’t offer a built-in way to do this, we’ll just resort to monitoring iOS's Reachability API.

like image 555
melsam Avatar asked Apr 09 '14 22:04

melsam


1 Answers

They have a section of their docs devoted to this here.

Basically observe the .info/connected ref

Firebase* connectedRef = [[Firebase alloc] initWithUrl:@"https://SampleChat.firebaseIO-demo.com/.info/connected"];
[connectedRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot, NSString *prevName) {
    if([snapshot.value boolValue]) {
        // connection established (or I've reconnected after a loss of connection)
    }
    else {
        // disconnected
    }
}];
like image 104
Logan Avatar answered Sep 28 '22 07:09

Logan