我正在创建聊天视图,以下是我的代码从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];
}
}];
}
}];
}
每当我单击文本字段中的"发送"按钮后,请再次调用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]}];
}
下面是我的桌面代码,
- (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;
}
我找不到为什么每当我将新孩子添加到DB时都会被调用。
多次被调用的不是您的viewDidLoad
,而是观察块(充当单独的函数)。
[.. observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
根据文档,FIRDataEventTypeValue
-"阅读并聆听对路径的整个内容的更改"。因此,只要您的firebase节点中发生更改,就会调用您的块。
顺便说一句,如果您只想将块称为一次,这里有一个示例 - 您需要使用方法observeSingleEventOfType:withBlock:withCancelBlock:
(或observeSingleEventOfType:withBlock:
)而不是observeEventType:withBlock:
我认为您必须检查此行或请分享。
FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId];
在此课程中,在Childbyautoid中,您的班级(父/超级班)可能会再次加载。在您之间可以检查此内容以获取参考。
ViewDidload两次称为