在Swift中向firebase firestore数据库添加一个字段



我正试图向我的服务结构添加一个新字段(标签(,但在Xcode中出现错误"在作用域"中找不到"hashtags";下面是我的代码。

import SwiftUI
import Firebase
import FirebaseFirestoreSwift
struct FeedTry: Identifiable, Decodable {
@DocumentID var id: String?
let caption: String
let myhashtags: String  //Added this new field
let timestamp: Timestamp
let uid: String
var likes: Int
var saves: Int

var user: User?
var didLike: Bool? = false
var didSave: Bool? = false
}

以下是我的服务视图

struct UploadTryService { 
func uploadTry(caption: String, completion: @escaping(Bool) -> Void) {
guard let uid = Auth.auth().currentUser?.uid else { return }

let data = ["uid": uid,
"caption": caption,
"hashtags": myhashtags, //getting the error here
"likes": 0,
"saves": 0,
"timestamp": Timestamp(date: Date())
] as [String : Any]

Firestore.firestore().collection("try").document().setData(data) { error in
if let error = error {
print("DEBUG: Failed to upload try with error: (error.localizedDescription)")
completion(false)
return
}

completion(true)
}
}

}

在网上和文档中检查,我还没有找到修复它的方法。

就像您对caption所做的那样,您可以向uploadTry传递一个参数,其中myhashtags:的值

struct UploadTryService { 
func uploadTry(caption: String, myhashtags: String, completion: @escaping(Bool) -> Void) { //<-- Here
guard let uid = Auth.auth().currentUser?.uid else { return }

let data = ["uid": uid,
"caption": caption,
"myhashtags": myhashtags, //getting the error here
"likes": 0,
"saves": 0,
"timestamp": Timestamp(date: Date())
] as [String : Any]

Firestore.firestore().collection("try").document().setData(data) { error in
if let error = error {
print("DEBUG: Failed to upload try with error: (error.localizedDescription)")
completion(false)
return
}

completion(true)
}
}
}

这意味着在你的方解石中,你也需要包括它:

uploadTry(caption: "Caption", myhashtags: "Hashtags here", ...)

另一种选择(取决于你想要的(是只通过一个空的String:

let data = ["uid": uid,
"caption": caption,
"myhashtags": "",
"likes": 0,
"saves": 0,
"timestamp": Timestamp(date: Date())

请注意,在这两种情况下,我都将dictionary键更改为myhashtags,因为您在模型中就是这样命名的。你可以选择任意一个键——只要确保它们匹配即可。

最新更新