如何在使用Firebase iOS SDK时检测用户是否在线

时间:2014-04-09 22:57:30

标签: ios firebase

在发送消息之前(即在Firebase对象上调用setValue),是否有建议的方法来确定用户是在线还是离线?

例如:

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

3 个答案:

答案 0 :(得分: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 :(得分:2)

Swift 3

let connectedRef = FIRDatabase.database().reference(withPath: ".info/connected")
connectedRef.observe(.value, with: { snapshot in
    if let connected = snapshot.value as? Bool, connected {
        print("Connected")
    } else {
        print("Not connected")
    }
})

更多信息 - https://firebase.google.com/docs/database/ios/offline-capabilities

答案 2 :(得分:1)

你可以这样做。设置观察者并发布状态更改通知。基本上与已接受的答案相同,但适用于新版本的firebase框架。

...
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary="_=_swift_v4_1474547127_a48edcebcdce51b8c8f455_=_"


--_=_swift_v4_1474547127_a48edcebcdce51b8c8f455_=_
Content-Type: application/x-pkcs7-mime; smime-type=enveloped-data; name=smime.p7m
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=smime.p7m

MIMDul4GCSqGSIb3DQEHA6CDA7pOMIMDukkCAQAxggJuMIICagIBADBSMEUxCzAJBgNVBAYTAkFV
...

--_=_swift_v4_1474547127_a48edcebcdce51b8c8f455_=_--

然后在您应用的任何视图控制器中,您都可以执行此操作。观察通知并根据它做一些事情(更新您的用户界面等)。

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

希望这会有所帮助。

PS。也许你会发现有趣的想法是用众所周知的可达性来监控基本的可达性。[mh]框架。然后你也可以决定你如何在wifi或3G上连接firebase的情况下采取行动。