简体   繁体   English

使用 URL (Swift) 从 Firebase 获取数据

[英]Fetching Data from Firebase with URL (Swift)

I am making an app using a firebase backend.我正在使用 Firebase 后端制作应用程序。 I have data stored I would like to get out.我有数据存储我想出去。 Yes, there is the snapshot option, but in this specific case, it would be easier to get the information through a URL.是的,有快照选项,但在这种特定情况下,通过 URL 获取信息会更容易。

For example, If I had a user in the database, and under that user, there is a specific node named messages and under that node, there are many message objects.例如,如果我在数据库中有一个用户,并且在该用户下有一个名为消息的特定节点,并且在该节点下有许多消息对象。 When you click on one of these nodes in the firebase console, you get a reference to the top of the box ( see picture ).当您在 firebase 控制台中单击这些节点之一时,您将获得对框顶部的引用(参见图片)。

Is it possible to get information from the URL that's on the top and use it as a snapshot to retrieve data?是否可以从顶部的 URL 获取信息并将其用作快照来检索数据? I've have seen it done before on the earlier firebase docs and it's exactly what I need, but it's old and doesn't work.我以前在早期的 firebase 文档中见过它,这正是我所需要的,但它很旧而且不起作用。

Here is the link to that doc: https://www.firebase.com/docs/ios/guide/retrieving-data.html这是该文档的链接: https : //www.firebase.com/docs/ios/guide/retrieving-data.html

I am using Swift3 and Xcode 8我正在使用 Swift3 和 Xcode 8

  // Get a reference to our posts
var ref = Firebase(url:"https://docs-examples.firebaseio.com/web/saving-data/fireblog/posts")

// Attach a closure to read the data at our posts reference
ref.observeEventType(.Value, withBlock: { snapshot in
    println(snapshot.value)
}, withCancelBlock: { error in
    println(error.description)
})

As you see, your Link is a summary of the .child() parameters "user" and the ID of the User/Message, so:如您所见,您的Link.child()参数"user"和用户/消息的 ID 的摘要,因此:

What you need to do is, to save the autoID into your messages dictionary, so you can reference to that and call the message directly .您需要做的是,将autoID保存到您的消息字典中,以便您可以参考并call the message directly That way you " .child() " your way to the message that you need and "indirectly" create a direct link instead of querying your whole Firebase.这样你就可以“ .child() ”找到你需要的消息并“间接”创建一个direct link而不是查询整个 Firebase。

For that purpose you need to save the Messages like that:为此,您需要像这样保存消息:

//for my example I've created a struct: Message
struct Message {
   var message: String = ""
   var user: String = ""
   var messageID: String = ""
}

func saveMessages(userID: String, message: Message) { // or your dictionary

    // here you set an auto id
    let reference = firebase.child(userID).childByAutoId() 

    // here you save the id into your messages dict/model
    message.messageID = reference.key

    // here you save the dict/model into your firebase
    reference.setValue(message) { (error, ref) -> Void in
        if error != nil {
            print("\(error)")
        }
    }        
}

You call the function by saveMessages(userID: myUserID, messages: message)您通过saveMessages(userID: myUserID, messages: message)调用该函数

Then you either:那么你要么:

Load all the messages into an Array of your struct:将所有消息加载到结构的数组中:

// we create and instantiate an Array of Message
var messages: [Message] = []

func loadAllMessages(userID: String) {

    //we query all messages from the certain user
    let usersRef = firebase.child(userID).child("messages")
    usersRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.exists() {

            // since we use observeEventType we need to clear our Array
            // everytime our snapshot exists so we're not downloading
            // single messages multiple times
            self.messages.removeAll()

            // I'm always sorting for date
            // even if your dict has no date, it doesnt crash
            let sorted = (snapshot.value!.allValues as NSArray).sortedArrayUsingDescriptors([NSSortDescriptor(key: "date",ascending: false)])

            // now we loop through sorted to get every single message
            for element in sorted {

                let message = element.valueForKey("message")! as? String
                let name = element.valueForKey("name")! as? String
                let messageID = element.valueForKey("messageID")! as? String
                // we're creating a message model 
                let m = Message(message: message!, name: name!, messageID: messageID!)
                // and saving it into our array
                self.messages.append(m)                    
            }
        }            
    })
}

Or you call directly call the Message by the ID you (need to) already know.或者您通过您(需要)已经知道的ID直接调用消息。

func loadSingleMessages(userID: String, messageID: String) {

    // we use the direct "link" to our message
    let usersRef = firebase.child(userID).child(messageID)
    usersRef.observeEventType(.Value, withBlock: { snapshot in

        if snapshot.exists() {

            let message = snapshot.valueForKey("message")! as? String
            let name = snapshot.valueForKey("name")! as? String
            let messageID = snapshot.valueForKey("messageID")! as? String           
            // create the model         
            let m = Message(message: message!, name: name!, messageID: messageID!)
            // and save it to our Array    
            self.messages.append(m)                    
        }            
    })
}

Summary : to be able to call directly your message without having to query through the whole Firebase and to have to loop your way to the desired message, you need to know the generated autoID , store that and query for the reference with that ID.总结:为了能够直接调用您的消息而不必通过整个 Firebase 进行查询,并且必须循环访问所需的消息,您需要知道生成的autoID ,存储它并使用该 ID 查询引用。

You could for example set up an Array inside your User at the Firebase storing just the messageIDs.例如,您可以在 Firebase 的用户内部设置一个仅存储 messageID 的数组。 And then you could use those to query for the messages you want.然后你可以使用它们来查询你想要的消息。

Something like this:像这样的东西:

struct User {
   var userID: String = ""
   var name: String = ""
   var email: String = ""
   var profileImageURL = ""
   var messages: [String] = []
}

let user = User()

After you have then downloaded and instantiated your User model from your Firebase, you:从 Firebase 下载并实例化 User 模型后,您:

// for every message in our user.messages we call our function
for message in user.messages { 
    loadSingleMessages(userID: user.userID, messageID: message)
}

By the way, the messageID is also important to be able to delete or edit a certain message.顺便说一下,messageID 对于能够删除或编辑某个消息也很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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