首页 > 解决方案 > 创建事件后将信息推送到 Firebase(Firebase-Realtime-Database)

问题描述

我正在尝试创建一个应用程序,用户可以在其中查看事件列表,决定他们想要加入的事件,单击该特定事件,然后加入它。我要解决的部分是创建活动的人想要查看哪些人加入了它。我知道如何获取人们的电子邮件,但不知道如何在特定事件中将其推送到 firebase。

这没有使用 Firestore

有人创建事件: 在此处输入图像描述

然后其他人在表格视图中看到该事件: 在此处输入图像描述

然后用户可以单击事件以获取更多信息: 在此处输入图像描述

我现在想做的是当人们注册一个活动时,我想保存他们的电子邮件并将其推送到 firebase,它将成为该活动的一部分: 在此处输入图像描述

为了进一步说明,这是我用来将事件详细信息推送到 firebase 的代码:

@IBAction func registerEvent(_ sender: UIButton) {
    //push stuff to firebase
    let eventName = eventTitle.text!
    let eventDB = Database.database().reference().child("Events")
    let eventDict = ["EventTitle": eventTitle.text!, "numPeople": numberOfPeople.text!, "EventDescription": EventDescription.text!]
    
    eventDB.child(eventName).setValue(eventDict){
        (error, reference) in
        if(error != nil){
            print(error!)
        }
    }
    
}

我需要将注册事件的用户的电子邮件推送到 firebase 数据库,但此操作需要在不同的视图控制器中进行

如果我需要澄清更多,请告诉我

标签: iosswiftfirebasefirebase-realtime-database

解决方案


有几种不同的方法可以做到这一点,这实际上取决于您使用的是实时数据库还是使用 Firestore。以下信息将使用 Firestore。

第一:配置您的数据库并为要发布的事件创建路径。

// Create a path to the events DB
let eventsDB = Firestore.firestore().collection("events") 

// It is helpful to initialize your object with an id that way you can get it later
let eventID = eventsDB.document().documentID 

// Initialize your event with the eventID as an identifier 
let event = Event(id: eventID, etc.....)

2nd:将数据发布到firestore

// Turn your event into a dictionary 
// Your class or struct should have a data representation
let eventData = event.jsonRepresentation

// Create a path to prepare to publish to firestore
let path = Firestore.firestore().collection("users").document(id)

// Set the data
path.setData(value) { (error) in
     if let error = error {
          // There was an error handle it here
          return
     }
    // Anything passed this points means the data has been set
}

现在,当您获取和序列化数据时,您可以访问标识符属性并更新该特定文档。假设您的活动的参与者存储了他们的 firebase uid,那么您可以根据您构建用户模型的方式引用他们的信息。

第 3 步:更新活动,如果您的活动没有参加的财产,请创建它。还可以在此处查看 firebase 交易。我不会在这里使用它,但它是一个很好的资源。https://firebase.google.com/docs/firestore/manage-data/transactions#transactions

// Append the new attending user to the old event 
let newEvent = event.attendees.append("some_unique_id_goes_here")

// Create a path
let path = firestore.firestore().collection("events").document(newEvent.identifer)

// Update the document at that path
dbPath.setData([attendingKey: newEvent.attendees], merge: true) { (error) in
    if let e = error {
        // There was an error handle it here
        return
    }
        // It was updated successfully 
}

推荐阅读