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

5

在发送消息(即在 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个回答

5
他们的文档中有一部分是关于这个的,可以在这里找到。
基本上观察 .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
    }
}];

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
您可以这样做。设置观察器并在状态更改时发布通知。基本上与接受的答案相同,但适应了新版本的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];
}

希望这会对您有所帮助。

附注:也许您会发现使用众所周知的reachability.[mh]框架监测基本可达性是个有趣的想法。那么当Firebase连接到WiFi或3G时,您也可以决定如何操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接