[英]viewDidLoad getting called every time a child is added to firebase database
我正在創建一個聊天視圖,下面是從數據庫獲取消息的代碼,
- (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];
}
}];
}
}];
}
在鍵入內容后,每當我單擊文本字段中的發送按鈕時,都會再次調用viewDidLoad,它將再次向self.arr_text添加數據。 以下是我的發送按鈕點擊代碼,
- (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]}];
}
以下是我的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;
}
每當我向數據庫中添加新的子代時,我都找不到為什么調用它的原因。
不是您的viewDidLoad
會被多次調用,而是它的觀察塊(充當單獨的函數)。
[.. observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
根據文檔 FIRDataEventTypeValue
“讀取和偵聽路徑的整個內容。”,因此,只要在Firebase節點中發生更改,就會調用您的塊。
順便說一句,如果您希望僅一次調用該塊,那么這里有一個示例-您需要使用observeSingleEventOfType:withBlock:withCancelBlock:
(或observeSingleEventOfType:withBlock:
而不是observeEventType:withBlock:
我認為您必須檢查此行或分享。
FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId];
在此情況下,此類在childByAutoId中發生的情況,您的類(父級/超級類)可能會再次加載。 兩者之間可以檢查一下以供參考。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.