Firebase问题中手动输入的数据

时间:2018-07-19 23:54:25

标签: ios swift firebase firebase-realtime-database

我正在手动将数据输入数据库,唯一没有从数据库传递过来的变量是作者,我不知道我要去哪里。

func getAllArticles(handler: @escaping (_ articles: [Article])-> ()){

    var articleArray = [Article]()
    REF_ARTICLES.observeSingleEvent(of: .value) { (articleMessageSnapshot) in
        guard let articleMessageSnapshot = articleMessageSnapshot.children.allObjects as? [DataSnapshot] else {return}

        for article in articleMessageSnapshot {

            let content = article.childSnapshot(forPath: "content").value as? String ?? "no content"
            let author = article.childSnapshot(forPath: "author").value as? String ?? "no author"
            let twitterHandle = article.childSnapshot(forPath: "twitterHandle").value as? String ?? "none"
            let articleTitle = article.childSnapshot(forPath: "articleTitle").value as? String ?? "no title"
            let date = article.childSnapshot(forPath: "date").value as? String ?? "no date"

            let article = Article(content: content, author: author, twitterHandle: twitterHandle, ArticleTitle: articleTitle, date: date)
            articleArray.append(article)
        }
        handler(articleArray)
    }
}

enter image description here

3 个答案:

答案 0 :(得分:1)

我也在开发类似的应用程序,其中我将数据存储到Firebase并进行检索。我使用以下方法从Firebase数据库中获取数据。请尝试一次。

func getAllArticles(handler: @escaping (_ articles: [Article])-> ()) { Database.database().reference().child("Articles").observe(.childAdded, with: { (snapshot) in print("articles = \(snapshot)") if let dict = snapshot.value as? [String: Any] { let article = Article() article.articleTitle = dict["articleTitle"] as? String article.author = dict["author"] as? String article.twitterHandle = dict["twitterHandle"] as? String article.date = dict["date"] as? String article.content = dict["content"] as? String self.articleArray.append(article) } handler(articleArray) }, withCancel: nil) }

答案 1 :(得分:1)

请查看下面的代码

var articleArray = [Article]()


        //REF_ARTICLES
        let ref = Database.database().reference().child(“articles”)
        ref.observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            guard let dictionary = snapshot.value as? [String : AnyObject] else {
                return
            }

            let articleObj = Article()
            articleObj.Content = dictionary["content"] as? String
            articleObj.Author = dictionary["author"] as? String
            articleObj.Twitterhandle = dictionary["twitterHandle"] as? String
            articleObj.Title = dictionary["articleTitle"] as? String
            articleObj.Date = dictionary["date"] as? String

            self. articleArray.append(articleObj)


        }, withCancel: nil)
    }

答案 2 :(得分:0)

我不确定潜在的问题是什么,但我通过从Firebase树中删除“作者”然后再添加回来解决了问题