当我按下JSQMessagesViewController中的发送按钮时,为什么会出现2条消息

时间:2017-02-08 17:07:30

标签: ios firebase firebase-realtime-database jsqmessagesviewcontroller

这是我的didpresssend逻辑 - 视图中出现了2条消息,但是当刷新页面时,我的消息数组中实际上只有1条消息。

- (void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text senderId:(NSString *)senderId senderDisplayName:(NSString *)senderDisplayName date:(NSDate *)date {

    JSQMessage *message = [[JSQMessage alloc] initWithSenderId:senderId senderDisplayName:senderDisplayName date:date text:text];

    NSDictionary *firebaseMessage = @{@"avatar":self.avatarURL,@"handle":senderDisplayName,@"message":text,@"profileId":self.profID,@"timestamp":[self getTimestamp]};
    [[self.threadRef childByAutoId] setValue:firebaseMessage withCompletionBlock:^(NSError * _Nullable error, FIRDatabaseReference * _Nonnull ref) {
        if (!error) {
            [self.messages addObject:message];
            [self finishSendingMessageAnimated:YES];
            [self sendToServer:text];
        } else {
            //Message Failed
        }
    }];
}

1 个答案:

答案 0 :(得分:0)

它与异步执行的操作有关 - 现在,我可以立即发布消息,然后在Firebase操作失败时删除消息:

但有人知道为什么会这样吗?它与JSQMessage数据源的工作方式有关吗?

- (void)didPressSendButton:(UIButton *)button withMessageText:(NSString *)text senderId:(NSString *)senderId senderDisplayName:(NSString *)senderDisplayName date:(NSDate *)date {

    JSQMessage *message = [[JSQMessage alloc] initWithSenderId:senderId senderDisplayName:senderDisplayName date:date text:text];
    [self.messages addObject:message];
    [self finishSendingMessageAnimated:YES];

    NSDictionary *firebaseMessage = @{@"avatar":self.avatarURL,@"handle":senderDisplayName,@"message":text,@"profileId":self.profID,@"timestamp":[self getTimestamp]};
    [[self.threadRef childByAutoId] setValue:firebaseMessage withCompletionBlock:^(NSError * _Nullable error, FIRDatabaseReference * _Nonnull ref) {
        if (!error) {
            [self sendToServer:text];
        } else {
            //Message Failed
            [self.messages removeObject:message];
            [self.collectionView reloadData];
        }
    }];
}