OGeek|极客世界-中国程序员成长平台

标题: ios - firebase onDisconnectSetValue 未按预期工作 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 12:56
标题: ios - firebase onDisconnectSetValue 未按预期工作

也许我理解 firebase 的 onDisconnectSetValue 错误,但我希望如下: 在firebase中,如果应用程序与firebase连接,我有一个值为“active”的值。如果连接丢失,我喜欢使用 onDisconnectSetValue 将值设置为 false。 为了测试它,我执行以下操作: - 使用互联网连接启动应用程序(设置 wlan) - 应用程序将“事件”设置为真 - 现在我切断互联网连接(关闭无线局域网)

现在我希望 firebase 自动将“Active”设置为 false,但该值保持为 true。

奇怪的是,如果我重新连接到互联网(再次打开 wlan),“事件”设置为 false。

代码:

Firebase *userAppActiveRef = [Firebase userAppActiveRef: user.entityID];
Firebase *infoRef = [Firebase infoRef];
[infoRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {
    if([snapshot.value boolValue]) {
        NSLog(@"connected");
        [userAppActiveRef setValue: @YES];
        [userAppActiveRef onDisconnectSetValue: @NO];
    } else {
        NSLog(@"not connected");
    }
}];

infoRef = .../.info/connected

我做错了什么或者 onDisconnectSetValue 没有按照我的想法工作?



Best Answer-推荐答案


尝试这个稍微不同的方向(这是您发布的大部分代码的扩展版本)

这有两个部分。第 1 部分是应用程序知道自己是否已连接(并采取任何一种方式),第 2 部分是知道其他用户是否已连接:

    //keep track if the app is connected to firebase or not via isConnected 
    //  isConnected has KVO listeners in the classes so they can take
    //  action when the user disconnects or reconnects

    Firebase *connectedRef = [self.appRef childByAppendingPath".info/connected"];

    [connectedRef observeEventType:FEventTypeValue withBlock:^(FDataSnapshot *snapshot) {

        //KVO property will change if the app d/c's        
        self.isConnected = [snapshot.value boolValue]; 

        if ( self.isConnected ) {
            NSLog(@"connected");
            [thisUserStatusRef setValue"YES"];

        } else {
            NSLog(@"d/c'd!! Run for the hills!");
        }

    }];

通过此设置,应用知道何时连接,并将 thisUsersStatusRef 设置为 YES。

然后,设置 onDisconnect 以在用户断开连接时执行操作

[thisUserStatusRef onDisconnectRemoveValue];

这告诉服务器在客户端断开连接时删除 thisUsersStatusRef(您也可以设置为 NO)。

所以当用户连接时,thisUsersStatusRef 设置为 YES,当它断开连接时,该值被删除。

最后,让您的应用观察用户节点是否有任何更改 - 如果其他用户连接该应用,将会收到通知,如果他们断开连接,他们也会收到通知。

[usersRef observeEventType:FEventTypeChildChanged withBlock:^(FDataSnapshot *snapshot) {

   //the snapshot will contain the user that connected or disconnects
   //  so just test to see if status is YES or null

 }];

关于ios - firebase onDisconnectSetValue 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34400749/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://sqlite.in/) Powered by Discuz! X3.4