我正在创建一个聊天视图,下面是我从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]}];
}
下面是我的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;
}
每当我向db添加一个新子时,我都无法找到它被调用的原因。
答案 0 :(得分:3)
多次调用不是你的viewDidLoad
,它是观察块(它作为一个单独的函数)。
[.. observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){
根据documentation,FIRDataEventTypeValue
- “读取并侦听路径的整个内容的更改。”,因此只要firebase节点发生更改,您的块就会被调用。
顺便说一下,如果你想要只调用一次这个块,那么就有一个例子here - 你需要使用方法observeSingleEventOfType:withBlock:withCancelBlock:
(或observeSingleEventOfType:withBlock:
)代替observeEventType:withBlock:
答案 1 :(得分:1)
我认为您必须检查此行或请分享。
FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId];
这个类中发生了什么,在childByAutoId中,你的类(父/超类)可能会再次加载。在您之间可以查看此内容以供参考。