[英]viewDidLoad getting called every time a child is added to firebase database
I am creating a chat view and below is my code to get messages from the db, 我正在创建一个聊天视图,下面是从数据库获取消息的代码,
- (void)viewDidLoad {
FIRDatabaseReference *tenantRef = [[FIRDatabase database] reference];
[[[[tenantRef child:@"tenantAgreements"] child:userId] child:_propertyId ] observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
//If no previous agreement in teenant agreements for this user or no agreements for this property ID
if(snapshot.value == [NSNull null]) {
FIRDatabaseReference *agreementCreateReference = [[[FIRDatabase database] referenceWithPath:@"/agreements/"] childByAutoId];
agreementId = agreementCreateReference.key;
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url = [NSString stringWithFormat:@"https://krib-api-onbit.herokuapp.com/api/agreements?agreementId=%@&listingId=%@",agreementCreateReference.key,_propertyId];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:@"POST"];
[request setValue:idToken forHTTPHeaderField:@"X-FIREBASE-ID-TOKEN"];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *res = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[dataTask resume];
}
else{ //If already a agreements for this property for this user exist.
agreementId = snapshot.value;
FIRDatabaseReference *getMessagesRef = [[FIRDatabase database] referenceWithPath:[NSString stringWithFormat:@"/messages/%@",snapshot.value]];
[getMessagesRef observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * snapshot) {
NSLog(@"snapshotssnapshots %@",snapshot);
if(snapshot != NULL){
for(snapshot in snapshot.children){
[self.arr_text addObject:snapshot];
}
[self.tableView reloadData];
}
}];
}
}];
}
Whenever I click the send button in the text field after typing something the viewDidLoad is getting called again and it is adding data to the self.arr_text again. 在键入内容后,每当我单击文本字段中的发送按钮时,都会再次调用viewDidLoad,它将再次向self.arr_text添加数据。 Below is my code for send button click, 以下是我的发送按钮点击代码,
- (IBAction)getMessage:(id)sender {
FIRDatabaseReference *firebaseMessagesRef = [[FIRDatabase database] reference];
FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId];
[[[[firebaseMessagesRef child:@"messages"] child:agreementId] child:id.key] setValue:@{@"senderId":userId,@"text":_textField.text,@"timestamp":[FIRServerValue timestamp]}];
}
Below is my tableview code, 以下是我的tableview代码,
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"myCell";
ChatTableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
FIRDataSnapshot *snaps = [self.arr_text objectAtIndex:indexPath.row];
cell.mylabel.text = snaps.value[@"text"];
cell.mylabel.backgroundColor = [UIColor grayColor];
cell.mylabel.layer.masksToBounds = YES;
cell.mylabel.layer.cornerRadius = 8.0;
cell.myImg.layer.cornerRadius = cell.myImg.frame.size.width/2;;
cell.myImg.clipsToBounds = YES;
[cell.myImg setImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[profile valueForKey:@"photoUrl"]]]]];
return cell;
}
I can't find why it is getting called whenever I add a new child to the db. 每当我向数据库中添加新的子代时,我都找不到为什么调用它的原因。
It's not your viewDidLoad
that gets called multiple times, it's the observation block that does (which acts as a separate function). 不是您的viewDidLoad
会被多次调用,而是它的观察块(充当单独的函数)。
[.. observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
According to the documentation , FIRDataEventTypeValue
- "Read and listen for changes to the entire contents of a path.", so your block will get called whenever a change occurs in your firebase node. 根据文档 FIRDataEventTypeValue
“读取和侦听路径的整个内容。”,因此,只要在Firebase节点中发生更改,就会调用您的块。
By the way, if you want the block to be called just once, there's an example here - you'll need to use the method observeSingleEventOfType:withBlock:withCancelBlock:
(or observeSingleEventOfType:withBlock:
) instead of observeEventType:withBlock:
顺便说一句,如果您希望仅一次调用该块,那么这里有一个示例-您需要使用observeSingleEventOfType:withBlock:withCancelBlock:
(或observeSingleEventOfType:withBlock:
而不是observeEventType:withBlock:
I think you must check this line or please share it. 我认为您必须检查此行或分享。
FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId];
Here what is happening in this class, in childByAutoId, it might be possible that your class(parent/super class) is loading again. 在此情况下,此类在childByAutoId中发生的情况,您的类(父级/超级类)可能会再次加载。 Between you can check this for reference. 两者之间可以检查一下以供参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.