如何从Firebase中检索数据将它存储在下面给出的Swift代码中的TextView对象中?

时间:2017-02-09 18:22:41

标签: ios swift firebase firebase-realtime-database

以下是我的代码。我试图检索存储在firebase的政治表中的数据,并希望将其存储在Swift中的uitextview类的textview对象中。 create()函数将数据存储在Firebase表中。

import UIKit
import Firebase
import FirebaseDatabase

class PoliticsNewsViewController: UIViewController{
    @IBOutlet weak var Image: UIImageView!
    @IBOutlet weak var textView: UITextView!
    var ref:FIRDatabaseReference!

    override func viewDidLoad()
    {
        super.viewDidLoad()

        //Retrieval and insertion must done here currently
         create()
    }

    func create()
    {
        //let date="9 feb 2017"
        let text="Sidhu joins congress"
        let aapNews="Arvind kejriwal now in race of wining wining punjab elections as he is gaining 70% seats in punjab"
        let BJPNews="BJP sufeers major blow in punjab due to demonatization gaining only 40 seats"
        ref=FIRDatabase.database().reference()
        ref.child("Politics News Table").childByAutoId().setValue(["Text" : text,"AAP news" : aapNews,"BJP News" : BJPNews])
    }

2 个答案:

答案 0 :(得分:1)

为了从firebase获取数据,您应该使用firebase引用中的observe方法。你提供了一个闭包,什么时候监听,每次数据库中的数据发生变化时都会调用它。

看看这个例子

ref.observe(FIRDataEventType.value, with: { snapshot in
        guard let info = snapshot.value as? [String : AnyObject], let textToShow = info["Text"] as? String else {
            return
        }
        // The snapshot is an object from firebase that is castable to
        // an array
        // The info array contains the information that you database has 
        // under the child that your reference has

        textView.text = textToShow
        //Here the textView has updated the text
    })

有关更多信息,例如可用的eventTypes,请查看以下链接:

https://firebase.google.com/docs/database/ios/retrieve-data

答案 1 :(得分:0)

这里有一个更详细的答案,可以提供可能有用的正确答案。

假设我们有一个包含帖子的社交媒体应用。这是帖子节点

posts
  -Yiias9j9asd
    post: "a post about stuff"
    date: "20170209"
  -Yinjiisidd
    post: "another post about stuff"
    date: "20170210"

然后将代码读入所有帖子并将其打印到日志

let postsRef = ref.child("posts")
postsRef.observeSingleEvent(of: .value, with: { snapshot in
    for snap in snapshot.children {
        let postKey = postSnap.key //the key of each post
        let postSnap = snap as! FIRDataSnapshot //the child data snapshot
        let postDict = postSnap.value as! [String:AnyObject] //child data dict

        let post = postDict["post"] as! String
        let date = postDict["date"] as! String
        print("postKey: \(postKey) post: \(post)  date: \(date)")
        //now that you have the data, you can add it to a textView
        // textView.text = post for example
     }
})

请注意,节点键名称(如Yiias9j9asd)是使用childByAutoId创建的,通常是让Firebase创建谨慎节点名称的推荐方法。