我找不到一个很好的例子来更新这里的分类中的订阅者,如下面的模型。
struct Categories: Identifiable, Codable, Hashable {
var id : String?
var categories : [Category]?
}
struct Category : Identifiable, Codable, Hashable{
var id :String
var category_id: String?
var icon : String?
var textColor :String?
var backgroundColor :String?
var language : CategoryLanguage?
var subscribers: [String]? // <--- I want to add/remove/update the subscribers, which may or may not be in a specific index.
}
I tried:
let docData: [String: Any] = [
"categories": [
"category_id": topicName,
"subscriber": [
subscribers
]
]
]
这样可以吗?还是我需要添加其他内容?如何在数组的特定索引中添加订阅者?
我有一个类别列表,每个类别都有订阅者,我需要在特定类别中添加/删除/更新订阅者。由于
在firebase
中有两种执行方法。
-
using
FireStore
进口FirebaseFirestore
更新
func updateCategory(_ category: Category) {
let db = Firestore.firestore()
do {
try db.collection("categories").document("subscriber").setData(from: category. subscribers) // arr of subscriber
} catch {
print(error)
}
}
删除
func deleteCategory(_ category: Category) {
let db = Firestore.firestore()
db.collection("categories").document(category.subscribers[i]).delete()
}
注意:请确保在调用更新函数时,您的subscribers
应该更新
using
Database
进口FirebaseDatabase
更新
func updateCategory(_ arrOfDict:[[String:Any]]) {
Database.database(url: url).reference().child("categories").setValue(arrOfDict) { // url might be database url
(error:Error?, ref:DatabaseReference) in
if let error = error {
print("Data could not be update: (error).")
} else {
print("Data updated successfully!")
}
}
}
func deleteCategory(subscriberId:String){
let ref = Database.database(url: url).reference().child("categories")
ref.observeSingleEvent(of: .value) {snapshot in
if var categories = snapshot.value as? [[String: Any]]{
var positionToRemove = 0
for category in categories{
if let arrOfSubscriber = category["subscriber"] as? [String]{
for id in arrOfSubscriber {
if id == subscriberId {
break
}
positionToRemove += 1
}
}
}
categories.remove(at: positionToRemove)
ref.setValue(categories, withCompletionBlock: { error, _ in
guard error == nil else {
print(error)
return
}
print("deleted subscriber")
})
}
}
}