2017-02-23 44 views
0

我创建一个聊天视图和下面是我的代码从数据库获取信息,viewDidLoad中获取调用每次孩子被添加到firbase数据库

- (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; 
} 

我找不到为什么它获取调用每当我添加一个新的孩子分贝。

回答

3

这不是你的viewDidLoad被调用多次,它的观测块,做(充当一个单独的函数)。

[.. observeEventType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot){ 

按照documentationFIRDataEventTypeValue - “读,听更改为路径的全部内容。”,所以只要改变你的火力点的节点时您的块将被调用。

顺便说一句,如果你想在块中只调用一次,有一个例子here - 你需要使用的,而不是observeEventType:withBlock:

方法 observeSingleEventOfType:withBlock:withCancelBlock:(或 observeSingleEventOfType:withBlock:
1

我想你必须检查这一行或请分享它。

FIRDatabaseReference *id = [firebaseMessagesRef childByAutoId]; 

这里是什么在这个类中发生的事情,在childByAutoId,有可能您的类(父/超类)被再次加载。你可以检查这个参考。

viewDidLoad is called twice