简体   繁体   中英

Swift Array not being appended to

I'm trying to get a tableview to display parsed data, but the array that is supposed to be populating my tableview isn't being appended. Could someone take a quick look and let me know what I'm doing wrong?

import UIKit
import SwiftKeychainWrapper
import Firebase

class FeedVC: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet var tableView: UITableView!

var posts = [Post]()

override func viewDidLoad()
{
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self


    DataService.ds.REF_POSTS.observeEventType(.Value, withBlock: { snapshot in
        if let snapshot = snapshot.children.allObjects as? [FIRDataSnapshot]
        {
            for snap in snapshot
            {

                if let postDict = snap.value as? Dictionary<String, AnyObject>
                {
                    let key = snap.key
                    let post = Post(postID: key, postData: postDict)
                    self.posts.append(post)

                }
            }
        }
    })

    tableView.reloadData()


}

override func viewDidAppear(animated: Bool) {

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return posts.count
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

    let post = posts[indexPath.row]
    print("\(post.caption)")


    return tableView.dequeueReusableCellWithIdentifier("PostCell") as! PostCell
}






@IBAction func signOutBtnTapped(sender: UIButton) {

    KeychainWrapper.defaultKeychainWrapper().removeObjectForKey(KEY_UID)
    try! FIRAuth.auth()?.signOut()
    performSegueWithIdentifier("toSignInVC", sender: nil)
}


}

Thanks guys.

Your data retrieval appears to be an async operation, which probably does not finish before the table is rendered. Try reloading the table data on a new line after self.posts.append(post) or at the end of the completion block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM