2017-02-28 1 views
0

해당 게시물에 대한 게시물 및 의견이있는 앱을 만들고 있습니다. 그러나 사용자가 게시/의견을 올릴 때마다 UITableView에로드 된 후 게시 된 순서대로 표시되지 않습니다. 게시물 및 댓글에 타임 스탬프를 구현했지만이를 정렬하는 방법을 알 수 없습니다.Firebase 데이터베이스를 연대순으로 정렬하려면 어떻게해야합니까?

내 데이터베이스 :

"posts" : { 
    "47CCC57D-9056-4F5B-919E-F686065574A2" : { 
    "comments" : { 
     "99838A46-A84E-47E9-9D9C-E048543DC7C9" : { 
      "comment" : "Would you trade for a red one?", 
      "timestamp" : 1488315280579, 
      "commentID" : "99838A46-A84E-47E9-9D9C-E048543DC7C9", 
      "username" : "user" 
     } 
    }, 
    "description" : "Don't really need this anymore. Willing to go for less if I can get a trade", 
    "image" : "JLMzSuhJmZ.jpeg", 
    "postID" : "47CCC57D-9056-4F5B-919E-F686065574A2", 
    "price" : "$5", 
    "rating" : "8", 
    "title" : "title", 
    "uid" : "5U1TnNtkhegmcsrRt88Bs6AO4Gh2", 
    "username" : "user" 
}, 

가 어떻게 CommentViewController에 주석을 정렬 atttempting 오전 :

var postDetails: String? 
var posts = NSMutableArray() 

func loadData() { 
    FIRDatabase.database().reference().child("posts").child(postDetails!) 
       .child("comments").queryOrdered(byChild: "timestamp") 
       .observeSingleEvent(of: .value, with: { snapshot in 
       if let postsDictionary = snapshot.value as? [String: AnyObject] { 
        for post in postsDictionary { 
         self.posts.add(post.value) 
        } 
        self.tableView.reloadData() 
       } 
    }) 
} 


// Displays posts in postsDetailsTableView 
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "commentCell", for: indexPath) as! CommentTableViewCell 
     // Configure the cell... 
     let post = self.posts[indexPath.row] as! [String: AnyObject] 
     cell.selectionStyle = .none 
     cell.commentLabel.text = post["comment"] as? String 
     cell.usernameLabel.text = post["username"] as? String 
     return cell 
    } 
} 

나는 각 주석이 게시 된 순서에 너무 무엇을 할 수 있는가?

답변

0

문제 : 코드에서 스냅 샷을 반환하지만 순서가 느슨한 사전으로 변환합니다.

.value로 쿼리 할 때 키, 값 및 주문 정보가 스냅 샷에 포함되어 있지만 스냅 샷을 사전으로 변환하면 순서가 손실되므로 정확한 순서를 얻기 위해 어린이를 반복해야합니다. .

func loadData() { 
    FIRDatabase.database().reference().child("posts").child(postDetails!) 
       .child("comments").queryOrdered(byChild: "timestamp") 
       .observe(.value, with: { snapshot in 

       for child in snapshot.children { 
       print("child \(child)") 
       } 
    }) 
} 
+0

감사합니다. Jay. 'func loadData'를 예제로 대체해야합니까? 아니면 기존 함수에 코드를 추가해야합니까? – gabe

+0

@gabe 어느 쪽이든. 분명히 올바른 인쇄물을 보여주기 위해 내 print 문을 제거하고 배열에 필요한 것을 추가하는 코드로 대체해야합니다. 그 루프가 완료된 후, self.tableView.reloadData(). 열쇠는 올바른 순서를 유지하기 위해 snapshot.children을 반복합니다. – Jay

관련 문제