melsam melsam - 1 month ago 10x
iOS Question

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

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.


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

Basically observe the .info/connected ref

Firebase* connectedRef = [[Firebase alloc] initWithUrl:@""];
[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