在Swift中访问变量外部函数

时间:2017-12-03 20:55:02

标签: ios swift uitableview

我想访问"帖子"在这个函数之外,这样我就可以在函数外面调用tableview.reloaddata()了。每次键进入qeoquery时,代码都会调用tableview.reloaddata()。我想只重装一次。但是当我在viewDidLoad中尝试时,"发布"数组是空的。怎么办?

在职能范围内宣布的帖子:

var  posts = [Post]()

功能:

func fetchData(){


        geofireRef = Database.database().reference().child("LOCATION")
        geofire = GeoFire(firebaseRef: geofireRef)
        let geoQuery = geofire?.query(at: myLoc, withRadius: 5.0)

        geoQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
            print("KEYKEY: \(key)")
            let dbRef = Database.database().reference().child("posts")
            let query = dbRef.queryOrdered(byChild: "\(key)")
            query.observeSingleEvent(of: .value, with: { (snapshot) in
                if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
                    for snap in snapshot {
                        if let postDict = snap.value as? Dictionary<String, Any>{
                            let key = snap.key
                            let post = Post.init(postKey: key, postData: postDict)


                            self.posts.append(post)
                        }
                    }
                }
                //self.posts.reverse()
                //self.tableView.reloadData()
                //print("POSTS: \(self.posts)")
            })
        })
    }

1 个答案:

答案 0 :(得分:0)

您可以在设置posts变量后立即调用tableView.reloadData()(就像您已注释掉的那样),或者您可以在posts变量上放置didSet观察者并在设置后重新加载tableView。如果您使用第二个选项,则需要重新构建解析器以仅将帖子设置一次,而不是一次附加一个项目。这看起来像这样:

var posts = [Post]() {
    didSet {
        self.tableView.reloadData()
    }
}

geoQuery?.observe(.keyEntered, with: { (key: String!, location: CLLocation!) in
        print("KEYKEY: \(key)")
        let dbRef = Database.database().reference().child("posts")
        let query = dbRef.queryOrdered(byChild: "\(key)")
        query.observeSingleEvent(of: .value, with: { (snapshot) in
            if let snapshot = snapshot.children.allObjects as? [DataSnapshot]{
                //Create a variable to hold posts until you've parsed all of them
                var foundPosts = [Post]()
                for snap in snapshot {
                    if let postDict = snap.value as? Dictionary<String, Any>{
                        let key = snap.key
                        let post = Post.init(postKey: key, postData: postDict)
                        foundPosts.append(post)
                    }
                }
                //Set the posts to be all the found posts
                self.posts = foundPosts
            }
        })
    })