2014-04-09 24 views
5

在发送消息(即在Firebase对象上调用setValue)之前,是否有建议的方式来确定用户是联机还是脱机?如何在使用Firebase iOS SDK时检测用户是否在线

例如:

[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. 

}]; 

我们需要这种在我们的iOS应用程序,因为如果他们走进例如隧道的用户可能会失去连接。如果Firebase没有提供内置的方式来执行此操作,那么我们只需要对iOS的Reachability API进行监控。

回答

5

他们有自己的文档专门为这个here.

的部分基本上观察.info/connected裁判

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 
    } 
}]; 
1

你可以做这样的事情。设置观察员并发送有关状态更改的通知。基本上与接受的答案相同,但适用于新版本的Firebase框架。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    ... 
    FIRDatabaseReference *ref = [[FIRDatabase database] referenceWithPath:@".info/connected"]; 
    [ref observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) { 
      NSString *value = snapshot.value; 
      NSLog(@"Firebase connectivity status: %@", value); 
      self.firebaseConnected = value.boolValue; 

      [[NSNotificationCenter defaultCenter] postNotificationName:@".fireBaseConnectionStatus" object:nil]; 
    }]; 
} 

然后,在你的应用程序的任何视图控制器,你可以做到这一点。观察通知并根据它做一些事情(更新你的UI等)。

- (void) fireBaseConnectionStatus:(NSNotification *)note 
{ 
     AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 
     [self updateButtons:app.firebaseConnected]; 
} 

- (void)viewDidLoad 
{ 
     [super viewDidLoad]; 
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(fireBaseConnectionStatus:) name:@".fireBaseConnectionStatus" object:nil]; 
} 

希望这会有所帮助。

PS。也许你会发现有一个有趣的想法,同时用熟知的可达性监视基本的可达性。[mh]框架。然后,您还可以决定如何在Firebase连接WiFi或3G时采取行动。

相关问题