对同一个新对象多次调用Firebase FEventTypeChildAdded回调

Liz*_*zza 0 authentication facebook objective-c ios firebase

我正在开发一个iOS应用程序,我已经在Firebase的登录 - 演示应用程序之上构建了我的项目.我可以通过Facebook进行身份验证,并与Firebase进行通信.当我按下注销按钮时,这是运行的代码:

- (void)logoutButtonPressed
{
     // logout of Firebase and set the current user to nil
     [self.simpleLogin logout];
     [self.ref unauth]; //Added this
     [self updateUIAndSetCurrentUser:nil];
     [self.items removeAllObjects];
     [self.tableView reloadData];
}
Run Code Online (Sandbox Code Playgroud)

它似乎可以解决问题.一切都重置,我的tableView被清除.当我重新登录时,我获得了与我的FB凭证相关联的数据,并且它填充了一切都很棒.我有一个textField和一个按钮,当我按下按钮时,textField的文本将保存到firebase并在本地更新.

当我在已经注销一次之后尝试在我的简单字符串列表中创建一个新条目时,问题就出现了.当我重新登录并尝试保存一个条目时,它会被保存到firebase一次(这是正确的),但我的回调被调用了两次!

[ref observeEventType:FEventTypeChildAdded withBlock:^(FDataSnapshot *snapshot) {
            // Add the chat message to the array.
            if (![snapshot.value isEqual:[NSNull null]]) {
                [self.items addObject:snapshot.value[@"text"]];
            }

            // Reload the table view so the new message will show up.
            [self.tableView reloadData];
        } withCancelBlock:^(NSError *error) {
            NSLog(@"%@", error.description);
        }];
Run Code Online (Sandbox Code Playgroud)

同一个对象快照在此块中显示两次,这意味着相同的对象将被添加两次到数组和我的tableView.如果我退出并重新登录,会变得更加奇怪.第三次,三份副本出现.第四次,四个项目等.这是我按下添加按钮时的代码:

- (IBAction)submitButtonPressed {
    if ([self.currentUser.provider isEqualToString:@"facebook"]) {
    Firebase *postRef = [[[self.ref childByAppendingPath:@"users"] childByAppendingPath:self.currentUser.uid] childByAppendingPath:@"posts"];

    NSString *statusText = [NSString stringWithFormat:@"Logged in as %@ (Facebook)",
                  self.currentUser.providerData[@"displayName"]];

    [[postRef childByAutoId] setValue:@{@"name" : statusText, @"text": self.textField.text}];
    }
}
Run Code Online (Sandbox Code Playgroud)

好像我可能没有完全退出Firebase或FB,但我不知道还有什么可以尝试.

什么会导致FEventTypeChildAdded回调被多次调用同一个新对象?

Fra*_*len 7

我从未使用过Firebase iOS SDK,但它很可能与其他SDK类似.

如果是这种情况,您注册的侦听器块将在用户注销时保持注册状态.然后,当用户再次登录时,您正在注册第二个事件侦听器.因此,从那一刻开始,您的代码块将为每个添加的子代执行两次.

您应该在用户注销时取消注册/取消事件侦听器(https://www.firebase.com/docs/ios/api/#firebase_removeAllObservers),或者如果您之前已经注册过它们,则不要再重新注册它们.

请参阅适用于iOS的Firebase指南,特别是有关拆分块的部分:https://www.firebase.com/docs/ios/guide/retrieving-data.html#section-detaching