从显示用户名称的文本字段在 firebase 数据库中创建一个名为用户 uid 的节点
Create a node named a user's uid in firebase database from a textfield that displays their name
我正在通过文本字段将信息发送到我的 firebase 数据库。我想创建一个节点 Users,然后在该节点下创建由用户的 uid 分隔的不同节点。在每个 UID 节点下,将有三个来自自定义单元格上的三个文本字段的文本字段的数据点。我希望能够在名称文本字段中键入用户名并让它发送他们各自的 UID。我目前有以下代码创建它:
@IBAction func sendButtonTapped(_ sender: Any) {
let companyNameC = companyNameTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let companyDescriptionC = companyDescriptionTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let today = Date()
let formatter1 = DateFormatter()
formatter1.dateFormat = "MMM d y"
print(formatter1.string(from: today))
let todaysDate = formatter1.string(from: today)
let storageRef = Storage.storage().reference(forURL: "I have my code here")
let imageName = companyNameTextFieldConsiderations.text!
let storageCompanyRef = storageRef.child("Company_Image_Considerations").child("\(todaysDate)").child(imageName)
let companyDescriptionTextFieldText = companyDescriptionTextFieldConsiderations.text
let dateToStart = startDateTextFieldConsiderations.text
let dateToDecide = endDateTextFieldConsiderations.text
let companyRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName)
let considerationInfluencerRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName).child("Users")
let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell) as! ConsiderationsCell
let nameTFC = cell.nameTextFieldConsiderations.text!
let feedTFC = cell.feedTextFieldConsiderations.text
let storyTFC = cell.storyTextFieldConsiderations.text
let compensationTFC = cell.compensationTextFieldConsiderations.text
let values = ["Name": nameTFC]
guard let imageSelected = self.CompanyImage.image else {
print ("Avatar is nil")
return
}
var dict: Dictionary<String, Any> = [
"Company Image": "",
"Company Description": companyDescriptionTextFieldText!,
"Start Date": dateToStart,
"Decision Date": dateToDecide
]
guard let imageData = imageSelected.jpegData(compressionQuality: 0.5) else {
return
}
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
storageCompanyRef.putData(imageData, metadata: metadata, completion:
{ (StorageMetadata, error) in
if (error != nil) {
return
}
storageCompanyRef.downloadURL { (url, error) in
if let metadateImage = url?.absoluteString {
dict["Company Image"] = metadateImage
companyRef.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
if error == nil {
print("Done")
return
}
}
)
}
}
storageRef.updateMetadata(metadata) { metadata, error in
if error != nil {
//Uh-oh, an error occurred!
} else {
// Updated metadata for 'images/forest.jpg' is returned
}
}
})
considerationInfluencerRef.updateChildValues(values as [AnyHashable : Any]) { (error, ref) in
if error != nil {
print(error ?? "")
return
}
self.navigationController?.popViewController(animated: true)
}
}
我希望它看起来像这样:
编辑:
这是动态原型单元格的图像:
你说的是使用名称文本域来命名数组中的对象。该对象有自己的数组,该数组由带有 # 的两个文本字段和带有 $?
的文本字段组成
编辑 2:
import UIKit
class ConsiderationCellModel: NSObject {
var feedNumberQauntity: String?
var storyNumberQuantity: String?
var compensationAmmount: String?
}
好吧,如果你看你想要的结构
root
Considerations
Jul 16 2020
COMPANY
Company Description: ...
users
some_user_uid
Compensation
你的代码不会那样做。
虽然它会正确写出您的公司信息
companyRef.updateChildValues(dict
这是公司名称、公司描述等
它有点偏离 rails 这里
let considerationInfluencerRef = Database.database().reference()
.child("Considerations")
.child("\(todaysDate)")
.child(imageName)
.child("Users")
因为它指向一个完全不同的节点
root
Considerations
todaysDate
imageName <- ??
Users
编辑
这里最大的问题是您试图从 tableView 中的单元格中读取数据 - 这些单元格是动态的,将被分配等等。
您应该将数据存储在数据源中,通常是数组。当用户将信息输入到您的 tableview 单元格中时,这应该反过来更新数组。因此,例如假设您有一个显示食谱的 tableView。将有一个数组将食谱和成分作为列表保存
class RecipeClass {
var name = ""
var ingredients = [String]()
}
var recipeArray = [RecipeClass]()
tableView 将有部分 headers,这是 RecipeClass 名称,然后行将是成分。
假设食谱要求将 1 杯糖作为第一种成分。因此,在表格视图中,用户单击该字段(与第 0 节的第 0 行相关的配方 0 的字段 0)并将其更改为 3/4 杯 - 此时数组中的 object 应该更新。
稍后,当用户点击保存时,当前正在显示的任何食谱索引(部分)都将从数据源数组中读取,然后写入 Firebase。
只要用户点击“添加行”,您就会在正在显示的菜谱中的数组中添加另一个 object 并刷新 tableView 的 row/cell 以反映新的 object
recipe.ingredients.add("") //"" is a placeholder or use "New Ingredient"
我不是 ASCII 艺术专家,但你的 UI 看起来像这样,成分可能是一个可滚动的 tableView,所以如果他们有 20 种成分,他们可以滚动浏览它们
Shepards Pie Save Button
3 Potato
1 Carrot
9 Peas
1Cup Gravy
如果他们想将 3 Potato 更改为 2 Potato,他们会点击 3 Potato 字段(如果是 tableView 则为单元格),输入 2 Potato 然后更新数据源数组。
我解决了一个问题。我需要更改代码行:
let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell) as! ConsiderationsCell
我需要使用 cellForRow
let index = IndexPath(row:0,section:0)
guard let cell = tableView.cellForRow(at:index) as? ConsiderationsCell else { print("Not shown") ; return }
这只解决了我的一个问题。现在我需要让它适用于多行。
这变成了一个多部分问题。解决后续问题
'如何创建一个 class,用那个 class 填充一个数组,更新该数组中的一个元素并将其写入 firebase。
这是带评论的答案。
class ConsiderationCellModel: NSObject {
var uid = "" //this will be used when reading in to keep track of which user it is
var name = "" //not sure what 'name' is but here ya go
var feedNumberQuantity = ""
var storyNumberQuantity = ""
var compensationAmount = ""
func getDict() -> [String: String] {
let dict = [
"Compensation": compensationAmount,
"NumberOfFeedPosts": feedNumberQuantity,
"NumberOfStoryPosts": storyNumberQuantity
]
return dict
}
}
var myArray = [ConsiderationCellModel]()
//suppose thre are 3 models, and user adds a new model, so it will be #4, which
// is index 3 in the array (0, 1, 2, 3)
let model = ConsiderationCellModel()
myArray.append(model)
//reload the tableView which will now display this empty model. User enters some
// data, update the model at index 3 from the entered data
model.name = "some name"
model.feedNumberQuantity = "10"
model.storyNumberQuantity = "20"
model.compensationAmount = "1.00"
//at some point later the user clicks Save, so get the current index
// retrieve the data from the model and store in Firebase.
let index = 3 //if there are 4 objects in the array and this is the one just added
//you can also get the .last element in the array
let modelData = myArray[index]
let dictToSave = modelData.getDict()
let usersRef = self.ref.child("users_test")
let childRef = usersRef.child("uid_0")
childRef.setValue(dictToSave)
结果结构为
users
uid_0 //a users uid
Compensation: "1.00"
NumberOfFeedPosts: "10"
NumberOfStoryPosts: "20"
我正在通过文本字段将信息发送到我的 firebase 数据库。我想创建一个节点 Users,然后在该节点下创建由用户的 uid 分隔的不同节点。在每个 UID 节点下,将有三个来自自定义单元格上的三个文本字段的文本字段的数据点。我希望能够在名称文本字段中键入用户名并让它发送他们各自的 UID。我目前有以下代码创建它:
@IBAction func sendButtonTapped(_ sender: Any) {
let companyNameC = companyNameTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let companyDescriptionC = companyDescriptionTextFieldConsiderations.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let today = Date()
let formatter1 = DateFormatter()
formatter1.dateFormat = "MMM d y"
print(formatter1.string(from: today))
let todaysDate = formatter1.string(from: today)
let storageRef = Storage.storage().reference(forURL: "I have my code here")
let imageName = companyNameTextFieldConsiderations.text!
let storageCompanyRef = storageRef.child("Company_Image_Considerations").child("\(todaysDate)").child(imageName)
let companyDescriptionTextFieldText = companyDescriptionTextFieldConsiderations.text
let dateToStart = startDateTextFieldConsiderations.text
let dateToDecide = endDateTextFieldConsiderations.text
let companyRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName)
let considerationInfluencerRef = Database.database().reference().child("Considerations").child("\(todaysDate)").child(imageName).child("Users")
let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell) as! ConsiderationsCell
let nameTFC = cell.nameTextFieldConsiderations.text!
let feedTFC = cell.feedTextFieldConsiderations.text
let storyTFC = cell.storyTextFieldConsiderations.text
let compensationTFC = cell.compensationTextFieldConsiderations.text
let values = ["Name": nameTFC]
guard let imageSelected = self.CompanyImage.image else {
print ("Avatar is nil")
return
}
var dict: Dictionary<String, Any> = [
"Company Image": "",
"Company Description": companyDescriptionTextFieldText!,
"Start Date": dateToStart,
"Decision Date": dateToDecide
]
guard let imageData = imageSelected.jpegData(compressionQuality: 0.5) else {
return
}
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
storageCompanyRef.putData(imageData, metadata: metadata, completion:
{ (StorageMetadata, error) in
if (error != nil) {
return
}
storageCompanyRef.downloadURL { (url, error) in
if let metadateImage = url?.absoluteString {
dict["Company Image"] = metadateImage
companyRef.updateChildValues(dict, withCompletionBlock: {
(error, ref) in
if error == nil {
print("Done")
return
}
}
)
}
}
storageRef.updateMetadata(metadata) { metadata, error in
if error != nil {
//Uh-oh, an error occurred!
} else {
// Updated metadata for 'images/forest.jpg' is returned
}
}
})
considerationInfluencerRef.updateChildValues(values as [AnyHashable : Any]) { (error, ref) in
if error != nil {
print(error ?? "")
return
}
self.navigationController?.popViewController(animated: true)
}
}
我希望它看起来像这样:
编辑:
这是动态原型单元格的图像:
你说的是使用名称文本域来命名数组中的对象。该对象有自己的数组,该数组由带有 # 的两个文本字段和带有 $?
的文本字段组成编辑 2:
import UIKit
class ConsiderationCellModel: NSObject {
var feedNumberQauntity: String?
var storyNumberQuantity: String?
var compensationAmmount: String?
}
好吧,如果你看你想要的结构
root
Considerations
Jul 16 2020
COMPANY
Company Description: ...
users
some_user_uid
Compensation
你的代码不会那样做。
虽然它会正确写出您的公司信息
companyRef.updateChildValues(dict
这是公司名称、公司描述等
它有点偏离 rails 这里
let considerationInfluencerRef = Database.database().reference()
.child("Considerations")
.child("\(todaysDate)")
.child(imageName)
.child("Users")
因为它指向一个完全不同的节点
root
Considerations
todaysDate
imageName <- ??
Users
编辑
这里最大的问题是您试图从 tableView 中的单元格中读取数据 - 这些单元格是动态的,将被分配等等。
您应该将数据存储在数据源中,通常是数组。当用户将信息输入到您的 tableview 单元格中时,这应该反过来更新数组。因此,例如假设您有一个显示食谱的 tableView。将有一个数组将食谱和成分作为列表保存
class RecipeClass {
var name = ""
var ingredients = [String]()
}
var recipeArray = [RecipeClass]()
tableView 将有部分 headers,这是 RecipeClass 名称,然后行将是成分。
假设食谱要求将 1 杯糖作为第一种成分。因此,在表格视图中,用户单击该字段(与第 0 节的第 0 行相关的配方 0 的字段 0)并将其更改为 3/4 杯 - 此时数组中的 object 应该更新。
稍后,当用户点击保存时,当前正在显示的任何食谱索引(部分)都将从数据源数组中读取,然后写入 Firebase。
只要用户点击“添加行”,您就会在正在显示的菜谱中的数组中添加另一个 object 并刷新 tableView 的 row/cell 以反映新的 object
recipe.ingredients.add("") //"" is a placeholder or use "New Ingredient"
我不是 ASCII 艺术专家,但你的 UI 看起来像这样,成分可能是一个可滚动的 tableView,所以如果他们有 20 种成分,他们可以滚动浏览它们
Shepards Pie Save Button
3 Potato
1 Carrot
9 Peas
1Cup Gravy
如果他们想将 3 Potato 更改为 2 Potato,他们会点击 3 Potato 字段(如果是 tableView 则为单元格),输入 2 Potato 然后更新数据源数组。
我解决了一个问题。我需要更改代码行:
let cell = tableView.dequeueReusableCell(withIdentifier: AddPersonCell) as! ConsiderationsCell
我需要使用 cellForRow
let index = IndexPath(row:0,section:0)
guard let cell = tableView.cellForRow(at:index) as? ConsiderationsCell else { print("Not shown") ; return }
这只解决了我的一个问题。现在我需要让它适用于多行。
这变成了一个多部分问题。解决后续问题
'如何创建一个 class,用那个 class 填充一个数组,更新该数组中的一个元素并将其写入 firebase。
这是带评论的答案。
class ConsiderationCellModel: NSObject {
var uid = "" //this will be used when reading in to keep track of which user it is
var name = "" //not sure what 'name' is but here ya go
var feedNumberQuantity = ""
var storyNumberQuantity = ""
var compensationAmount = ""
func getDict() -> [String: String] {
let dict = [
"Compensation": compensationAmount,
"NumberOfFeedPosts": feedNumberQuantity,
"NumberOfStoryPosts": storyNumberQuantity
]
return dict
}
}
var myArray = [ConsiderationCellModel]()
//suppose thre are 3 models, and user adds a new model, so it will be #4, which
// is index 3 in the array (0, 1, 2, 3)
let model = ConsiderationCellModel()
myArray.append(model)
//reload the tableView which will now display this empty model. User enters some
// data, update the model at index 3 from the entered data
model.name = "some name"
model.feedNumberQuantity = "10"
model.storyNumberQuantity = "20"
model.compensationAmount = "1.00"
//at some point later the user clicks Save, so get the current index
// retrieve the data from the model and store in Firebase.
let index = 3 //if there are 4 objects in the array and this is the one just added
//you can also get the .last element in the array
let modelData = myArray[index]
let dictToSave = modelData.getDict()
let usersRef = self.ref.child("users_test")
let childRef = usersRef.child("uid_0")
childRef.setValue(dictToSave)
结果结构为
users
uid_0 //a users uid
Compensation: "1.00"
NumberOfFeedPosts: "10"
NumberOfStoryPosts: "20"