我正在创建一个应用程序,首先要对用户进行身份验证,然后他们才能添加捕获的鱼的记录。
用户创建帐户时,会将它们添加到Firebase的“身份验证”部分,还将它们添加到实时数据库中的“用户”节点。这是auth写的样子:
func createUser(withEmail email: String, andPassword password: String, userCreationComplete: @escaping (_ status: Bool, _ error: Error?) -> ()) {
Auth.auth().createUser(withEmail: email, password: password) { (authDataResult, error) in
guard let authDataResult = authDataResult else {
userCreationComplete(false, error)
return
}
let userData = ["provider": authDataResult.user.providerID, "email": authDataResult.user.email]
DataService.instance.createDbUser(uid: authDataResult.user.uid, userData: userData)
userCreationComplete(true, nil)
}
}
private var _REF_BASE = DB_BASE
private var _REF_USERS = DB_BASE.child("users")
private var _REF_CATCHES = DB_BASE.child("catches")
func createDbUser(uid: String, userData: Dictionary<String, Any>) {
REF_USERS.child(uid).updateChildValues(userData)
}
我不知道是如何添加一条鱼记录的,该记录仅与添加该记录的用户绑定(每个用户只能查看自己的鱼获)。
我有一个鱼模型:
class Fish {
private var _fishSpecies: String
private var _fishWeight: String
private var _key: String
var fishSpecies: String {
return _fishSpecies
}
var fishWeight: String {
return _fishWeight
}
var key: String {
return _key
}
init(species: String, weight: String, key: String) {
self._fishSpecies = species
self._fishWeight = weight
self._key = key
}
}
这是我的“添加”按钮,它将需要获取用户添加的鱼类信息,并将其添加到特定用户下的实时数据库中:
@IBAction func addBtnPressed(_ sender: Any) {
guard let species = speciesTxtField.text
guard let weight = weightTxtField.text
guard let uid = Auth.auth().currentUser?.uid
//nest fish model in the realtime db under the specific user
}
要做我的应用程序应该做的事情,我还需要更新数据库规则吗?他们目前允许从任何经过身份验证的人进行读写。是否应该将它们更改为仅在uid匹配时才允许读取?
{
"rules": {
"$uid": {
".write": "auth.uid != null",
".read": "auth.uid != null"
}
}
}
编辑:
这是我的数据服务类中创建一条鱼记录并获取所有鱼记录的方法吗?看起来正确吗?我将如何在“添加”按钮操作中利用它?
func createFish(withSpecies species: String, andWeight weight: String, handler: @escaping (_ fishCreated: Bool) -> ()) {
REF_CATCHES.childByAutoId().updateChildValues(["species": species, "weight": weight])
handler(true)
}
func getAllFish(handler: @escaping (_ catchArray: [Fish]) -> ()) {
var fishArray = [Fish]()
REF_CATCHES.observeSingleEvent(of: .value) { (fishSnapshot) in
guard let fishSnapshot = fishSnapshot.children.allObjects as? [DataSnapshot] else { return }
for fish in fishSnapshot {
let species = fish.childSnapshot(forPath: "species").value as! String
let weight = fish.childSnapshot(forPath: "weight").value as! String
let cAtch = Fish(species: species, weight: weight, key: fish.key)
fishArray.append(cAtch)
}
handler(fishArray)
}
}