2017-05-05 13 views
1

Swift 3 및 Firebase - 사용자의 사용자 이름과 전자 메일 주소를 tableview 셀에서 성공적으로 가져올 수있었습니다. 그러나 사용자가 별도의보기 컨트롤러에서 사용자 이름을 변경하면 tableview가 업데이트되지 않고 이전 사용자 이름이 계속 표시됩니다. 내가 성공하지 않고 여러 위치에 tableview.reloadData()를 배치 시도Swift 3 및 Firebase - Tableview가 업데이트되지 않음

databaseRef.child("users").queryOrdered(byChild: "username").observe(.childAdded, with: { (snapshot) in 

     let key = snapshot.key 
     let snapshot = snapshot.value as? NSDictionary 
     snapshot?.setValue(key, forKey: "uid") 

     if(key == self.loggedInUser?.uid) 
     { 
      // don't add signed in user to array 
     } 
     else 
     { 
      var theUser = User() 
      theUser.key = key 
      theUser.fullname = snapshot?.value(forKey: "fullname") as? String 
      theUser.biography = snapshot?.value(forKey: "biography") as? String 
      theUser.location = snapshot?.value(forKey: "location") as? String 
      theUser.photoURL = snapshot?.value(forKey: "photourl") as? String 
      theUser.username = snapshot?.value(forKey: "username") as? String 
      self.arrayOfUsers.append(theUser) 
      //insert the rows 
      self.SearchUsersTableViewController.insertRows(at: [IndexPath(row:self.arrayOfUsers.count-1,section:0)], with: UITableViewRowAnimation.automatic) 

       self.tableView.reloadData() 

     } 
    }) 

: 아래의 코드에서 참조하시기 바랍니다. 나는 또한 시도했다 :

DispatchQueue.main.async { 
    self.tableView.reloadData() 
} 

성공없이. 나는 사용자 이름을 바꿀 때 사용자를 다시 추가 할 생각을했습니다. 그러나, 나는 오래된 것을 지우는 법을 몰랐다. 가장 좋은 해결책은 childChanged 형식의 관찰을 추가하는 것이라고 생각했습니다. 문제는 사용자 배열에서 사용자 이름을 변경 한 사용자의 색인을 찾을 수 없다는 것입니다.

누군가가 내가 문제를 해결하는 데 도움이된다면 감사 할 것입니다.

편집 : 나는 구조체 사용자가

: 나는 Priyamal 제안 코드를 사용한 .childChanged를 들어

struct User { 
    var username: String? 
    var photoURL: String? 
    var biography: String? 
    var fullname: String? 
    var location: String? 
    var key: String? 
} 

:

databaseRef.observe(.childChanged, with: { snapshot in 
     let ID = snapshot.key //this is the firebaseKey 
     if let index = self.arrayOfUsers.index(where: {$0.key == ID}) { 
      let changedPost = self.arrayOfUsers[index] 
      //update the values 
       self.tableView.reloadData() 
       print("Change!") 
     } 
    }) 

그러나, 나는 사용자 이름을 변경할 때, 나는 결코 "변화!" 내 콘솔에 출력; 따라서 테이블 뷰는 변경되지 않습니다.

답변

1

이벤트 유형을 childAdded에서 childChanged 으로 변경해야한다고 생각합니다. 변경된 경우에만 업데이트 된 값만 표시됩니다. 배열의 기존 요소를 업데이트해야합니다.

는 이제 업데이트가

databaseRef.observeEventType(.ChildChanged, withBlock: { snapshot in 
    let ID = snapshot.key //this is the firebaseKey 
    if let index = self. userArray.indexOf({$0.keyID == ID}) { 
    let changedPost = self. userArray[index] 
    //update the values 
    self.tableView.reloadData 
    } 

처음부터 사용이 방법에 UserArray로드 발생하는 경우 구조체는이 방법이 불려가는이

struct User { 
    var keyID : String? 
    var name : String? 
} 

    var userArray = [User]() //this represents the array holding user objects 

처럼 보인다하여 사용자를 가정하자.

databaseRef.child("users").queryOrdered(byChild: "username").observe(.value, with: { (snapshot) in 

     let key = snapshot.key 
     let snapshot = snapshot.value as? NSDictionary 
     snapshot?.setValue(key, forKey: "uid") 

     if(key == self.loggedInUser?.uid) 
     { 
      print("Should not be shown!") 
     } 
     else 
     { 
      self.usersArray.append(snapshot) 
      self.SearchUsersTableViewController.insertRows(at: [IndexPath(row:self.usersArray.count-1,section:0)], with: UITableViewRowAnimation.automatic) 

       self.tableView.reloadData() 

     } 
    }) 
+0

그러면 배열에 데이터가 채워지지 않습니다. .childAdded (.value조차도 포함하지 않음) –

+0

을 사용해 만 채울 수 있습니다. 이 작동해야합니다 – Priyamal

+0

오류가 발생합니다 : 형식 'NSDictionary?' 이 행에는 'keyID'멤버가 없습니다 : let index = self.usersArray.indexOf ({$ 0.keyID == ID}) –

0

문제를 성공적으로 해결했습니다. 인덱스를 얻은 후에 배열의 특정 위치에서 사용자를 업데이트하고 테이블 뷰에서 특정 행을 새로 고칠 필요가있었습니다.

databaseRef.child("users").queryOrdered(byChild: "username").observe(.childChanged, with: { (snapshot) in 
     let ID = snapshot.key 
     if let index = self.arrayOfUsers.index(where: {$0.key == ID}) { 
      let value = snapshot.value as? NSDictionary 
      self.arrayOfUsers[index].username = value?["username"] as? String 
      let indexPath = IndexPath(item: index, section: 0) 
      self.tableView.reloadRows(at: [indexPath], with: .top) 
     } 
    }) 
관련 문제