gpt4 book ai didi

ios - 我如何从某人点击的已创建单元格的 firebase 中提取 key

转载 作者:行者123 更新时间:2023-11-30 12:05:08 25 4
gpt4 key购买 nike

我如何从某人点击的已创建单元格(我正在使用 TableView)的 firebase 中提取 key ,并将其创建为本地变量?我想知道这一点,这样我就可以将 key 转移到下一个 View 中,这样我就可以制作通用 Storyboard,但文本字段会随着 key 而变化。这也意味着我想在一个 View Controller 中设置数据,然后将其发送到另一个 View Controller ,如果我为此使用相同的数据库(我),我需要在第二个 View Controller 上对其进行编辑。

我已经在第二个 View Controller 上得到了这么多(用于 firebase)

  refObjective = Database.database().reference().child("objective");


let bodyFire = refObjective.childByAutoId().child("body")
bodyFire.observeSingleEvent(of: .value, with: { (snapshot) in
let bodyOnFire = snapshot.value as? String
self.text?.text = bodyOnFire

})

以及整个 View 第一个/tableview Controller

//  WeeklyObjectivesEditorViewController.swift
// Studioso
//
// Created by Charles Porth on 8/29/17.
// Copyright © 2017 Studioso. All rights reserved.
//


import Foundation
import UIKit
import FirebaseCore
import FirebaseDatabase

class WeeklyObjectivesEditorViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet weak var View2: UITabBarItem!

@IBOutlet weak var toolbar1: UITextField!

//defining firebase reference var
var refToolbars: DatabaseReference!

var refToolbars2: DatabaseReference!
let arrayOfIDs: NSMutableArray = [""]

@IBOutlet weak var tableViewToolbar: UITableView!

//list to store all the artist
var toolbarList = [ToolbarModel]()



public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toolbarList.count

}



public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//creating a cell using the custom class
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! ViewControllerTableViewCell

//the artist object
let toolbar: ToolbarModel

//getting the artist of selected position
toolbar = toolbarList[indexPath.row]

//adding values to labels

cell.label.text = toolbar.toolbar1

//returning cell
return cell
}

@IBOutlet weak var scrollView: UIScrollView!

@IBOutlet weak var Remove: UIBarButtonItem!

@IBOutlet weak var add: UIBarButtonItem!

@IBAction func buttonToolbar(_ sender: UIButton) {
addToolbar()
restructureDBKeys()
//reloading the tableview
self.tableViewToolbar.reloadData()
}

override func viewDidLoad() {
super.viewDidLoad()
// Add this
tableViewToolbar.delegate = self
tableViewToolbar.dataSource = self

//getting a reference to the node artists
refToolbars = Database.database().reference().child("toolbars");

print(selectedKey + "this is the selected key")
dataPassedMedium = selectedKey

let bodyFire = refToolbars.childByAutoId().child("body")

//this is how you get it
refToolbars.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
self.arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
self.arrayOfIDs.add(ID as! String) //Will always be a string in Firebase


}
}
}
})


//observing the data changes
refToolbars.observe(DataEventType.value, with: { (snapshot) in

//if the reference have some values
if snapshot.childrenCount > 0 {

//clearing the list
self.toolbarList.removeAll()

//iterating through all the values
for toolbar in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let toolbarObject = toolbar.value as? [String: AnyObject]
let toolbarId = toolbarObject?["id"]
let toolbarToolbar1 = toolbarObject?["toolbar1"]
let toolbarBody = toolbarObject?["body"]
let toolbarTitle = toolbarObject?["title"]

// creating artist object with model and fetched values

//creating artist object with model and fetched values
let toolbar = ToolbarModel(id: toolbarId as! String?, toolbar1: toolbarToolbar1 as! String?, title: toolbarTitle as! String?, body: toolbarBody as! String?)


//appending it to list
self.toolbarList.append(toolbar)
}

//reloading the tableview
self.tableViewToolbar.reloadData()
}
})


}

func addToolbar(){
//generating a new key inside artists node
//and also getting the generated key
let key = refToolbars.childByAutoId().key

//creating artist with the given values
let toolbar = ["id":key,
"toolbar1": toolbar1.text! as String,

]

//adding the artist inside the generated unique key
refToolbars.child(key).setValue(toolbar)




}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}








{

var valueToPass:String! // #1 i added this one first
var selectedKey: String!

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
// Get Cell Label
let indexPath = tableView.indexPathForSelectedRow!
let currentCell = tableView.cellForRow(at: indexPath)! as! ViewControllerTableViewCell

// valueToPass = currentCell.label.text

//the artist object
//getting the artist of selected position
// toolbar = toolbarList[indexPath.row]
let destinationVC = AddNewObjectiveViewController()
destinationVC.transferRow = selectedKey

selectedKey = (arrayOfIDs[indexPath.row] as? String)!
print(selectedKey + "this is the selected key@ selected")
print(dataPassedMedium + "this is the dataPassedMedium key@ selected")

dataPassedMedium = selectedKey
self.performSegue(withIdentifier: "weeklyadd", sender: self)


}
func restructureDBKeys() {


// let arrayOfIDs: NSMutableArray = [""]
//this is how you get it
refToolbars.observeSingleEvent(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
self.arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
self.arrayOfIDs.add(ID as! String) //Will always be a string in Firebase


}
}
}
})

}


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// #2 used if let as? UINavigationController

let destinationVC = navigationController?.topViewController as? AddNewObjectiveViewController
// destinationVC?.transferRow = valueToPass
destinationVC?.transferRow = selectedKey

print("data should be transfered" )
dataPassedMedium = selectedKey

if let navigationController = segue.destination as? UINavigationController {
let destinationVC = navigationController.topViewController as? AddNewObjectiveViewController
destinationVC?.transferRow = selectedKey
print("data should be transfered" )
}

}







}
var dataPassedMedium: String!

和整个 View 第二个 Controller

//
// AddNewObjective.swift
// Studioso
//
// Created by Charles Porth on 9/21/17.
// Copyright © 2017 Studioso. All rights reserved.
//

import Foundation
import QuartzCore
import UIKit
import FirebaseCore
import FirebaseDatabase

class AddNewObjectiveViewController: UIViewController {

@IBOutlet var text : UITextView?
@IBOutlet var textfield : UITextField!

var transferRow = String()



//defining firebase reference var
var refObjective: DatabaseReference!





@IBAction func Save(_ sender: Any) {

print(transferRow + "String has been tranfered via tranferRow during save" )

}


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//not perimantent
self.text?.layer.borderWidth = 1
self.text?.layer.borderColor = UIColor.red.cgColor

refObjective = Database.database().reference().child("toolbar");

//transferRow = WeeklyObjectivesEditorViewController().selectedKey
transferRow = dataPassedMedium
// refObjective = Database.database().reference().child("toolbars");

// let bodyFire = refObjective.child("-KwSYtZU_EX1vFFeTI4g").child("body")

print(transferRow + "String has been tranfered via tranferRow")

let delayInSeconds = 4.0
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + delayInSeconds) {


}

}


func addObjective(){
//generating a new key inside artists node
//and also getting the generated key

//creating artist with the given values
let objective = ["id": self.transferRow,
"body": self.text?.text! as! String,
"title": self.textfield.text! as String
] as [String : Any]

//adding the artist inside the generated unique key
self.self.refObjective.child(self.transferRow).setValue(objective)




}




override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}






}

最佳答案

要收集在 tableView 中使用的键,您可以使用字典数组 - 您的偏好。

//This is the key that is desired.
let bodyFire = refObjective.childByAutoId().child("body")

didSelectRowAt 中,当您选择该键时:

让 selectedKey = arrayOfIDs[indexPath.row] 为?字符串

//
// WeeklyObjectivesEditorViewController.swift
// Studioso
//
// Created by Charles Porth on 8/29/17.
// Copyright © 2017 Studioso. All rights reserved.
//


import Foundation
import UIKit
import FirebaseCore
import FirebaseDatabase

class WeeklyObjectivesEditorView2ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {


@IBOutlet weak var toolbar1: UITextField!

@IBOutlet weak var View1: UITabBarItem!

//defining firebase reference var
var refToolbars2: DatabaseReference!
let arrayOfIDs: NSMutableArray = [""]

// @IBOutlet weak var label: UILabel!
@IBOutlet weak var tableViewToolbar: UITableView!

//list to store all the artist
var toolbarList = [View2ToolbarModel]()

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return toolbarList.count

}


public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
//creating a cell using the custom class
let cell1 = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! ViewControllerTableViewCell2

//the artist object
let toolbar: View2ToolbarModel

//getting the artist of selected position
toolbar = toolbarList[indexPath.row]



//adding values to labels

cell1.label.text = toolbar.toolbar1

//returning cell
return cell1
}



@IBOutlet weak var scrollView: UIScrollView!
//1 == up
// @IBOutlet weak var toolbar2: UITextField!
// @IBOutlet weak var toolbar3: UITextField!
// @IBOutlet weak var toolbar4: UITextField!
// @IBOutlet weak var toolbar5: UITextField!
// @IBOutlet weak var toolbar6: UITextField!
// @IBOutlet weak var toolbar7: UITextField!
// @IBOutlet weak var toolbar8: UITextField!
// @IBOutlet weak var toolbar9: UITextField!
// @IBOutlet weak var toolbar10: UITextField!
// @IBOutlet weak var toolbar11: UITextField!
// @IBOutlet weak var toolbar12: UITextField!
// @IBOutlet weak var toolbar13: UITextField!

@IBOutlet weak var Remove: UIBarButtonItem!

@IBOutlet weak var add: UIBarButtonItem!

/*
func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "WeeklyObjectivesViewController" {

let WeeklyObjectivesViewController = self.storyboard?.instantiateViewController(withIdentifier: "WeeklyObjectivesViewController") as! WeeklyObjectivesViewController
*/




//https://www.raywenderlich.com/139322/firebase-tutorial-getting-started-2

@IBAction func buttonToolbar(_ sender: UIButton) {
addToolbar()

//reloading the tableview
self.tableViewToolbar.reloadData()
}

override func viewDidLoad() {
super.viewDidLoad()
refObjective(of: .value, with: { (snapshot) in
if snapshot.value is NSNull{
//Handle errors
}
else{
arrayOfIDs.removeAllObjects()
if let dict = snapshot.value as? NSDictionary{
//dict.allKeys is all the IDs
for ID in dict.allKeys{
arrayOfIDs.add(ID as! String) //Will always be a string in Firebase
self.tableView.reloadData()
}
}
}
})

// Add this
tableViewToolbar.delegate = self
tableViewToolbar.dataSource = self


//getting a reference to the node artists
refToolbars2 = Database.database().reference().child("toolbarsView2");


//observing the data changes
refToolbars2.observe(DataEventType.value, with: { (snapshot) in

//if the reference have some values
if snapshot.childrenCount > 0 {

//clearing the list
self.toolbarList.removeAll()

//iterating through all the values
for toolbar in snapshot.children.allObjects as! [DataSnapshot] {
//getting values
let toolbarObject = toolbar.value as? [String: AnyObject]
let toolbarId = toolbarObject?["id"]
let toolbarToolbar1 = toolbarObject?["toolbar1"]


//creating artist object with model and fetched values
//let toolbar = ToolbarModel(toolbar1: "String?")

//creating artist object with model and fetched values
let toolbar = View2ToolbarModel(id: toolbarId as! String?, toolbar1: toolbarToolbar1 as! String?)


//appending it to list
self.toolbarList.append(toolbar)
}

//reloading the tableview
self.tableViewToolbar.reloadData()
}
})
// scrollView.contentSize = CGSize(width: view.frame.width, height: view.frame.height + 83)




}

func addToolbar(){
//generating a new key inside artists node
//and also getting the generated key
let key = refToolbars2.childByAutoId().key

//creating artist with the given values
let toolbar = ["id":key,
"toolbar1": toolbar1.text! as String,
// "toolbar2": toolbar2.text! as String,
// "toolbar3": toolbar3.text! as String,
// "toolbar4": toolbar4.text! as String,
// "toolbar5": toolbar5.text! as String,
// "toolbar6": toolbar6.text! as String,
// "toolbar7": toolbar7.text! as String,
// "toolbar8": toolbar8.text! as String,
// "toolbar9": toolbar9.text! as String,
// "toolbar10": toolbar10.text! as String,
// "toolbar11": toolbar11.text! as String,
// "toolbar12": toolbar12.text! as String,
]

//adding the artist inside the generated unique key
refToolbars2.child(key).setValue(toolbar)
// refToolbars.child(key).setValue(toolbar1)
// refToolbars.child(key).setValue(toolbar2)
// refToolbars.child(key).setValue(toolbar3)
// refToolbars.child(key).setValue(toolbar4)
// refToolbars.child(key).setValue(toolbar5)
// refToolbars.child(key).setValue(toolbar6)
// refToolbars.child(key).setValue(toolbar7)
// refToolbars.child(key).setValue(toolbar8)
// refToolbars.child(key).setValue(toolbar9)
// refToolbars.child(key).setValue(toolbar10)
// refToolbars.child(key).setValue(toolbar11)
// refToolbars.child(key).setValue(toolbar12)
//


//displaying message
// labelMessage.text = "toolbar"

//https://www.simplifiedios.net/firebase-realtime-database-tutorial/


}


override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}








// func prepareForSegue(segue: UIStoryboardSegue,sender: AnyObject!) {
// let segueName: String = segue.identifier!;
// if (segueName == "addButton") {
// let weeklyObjectivesViewController = segue.destination as! WeeklyObjectivesViewController;
//
//// weeklyObjectivesViewController.stringPassed1 = toolbar1.text
//
// }
// }
//
}

//
// AddNewObjective.swift
// Studioso
//
// Created by Charles Porth on 9/21/17.
// Copyright © 2017 Studioso. All rights reserved.
//

import Foundation
import QuartzCore
import UIKit
import FirebaseCore
import FirebaseDatabase

class AddNewObjectiveViewController: UIViewController {

@IBOutlet var text : UITextView?
@IBOutlet var textfield : UITextField!
var selectedKey = ""
var transferRow: String = ""
//defining firebase reference var
var refObjective: DatabaseReference!

//var textString: String!
//var textfieldString: String!


//https://developer.apple.com/library/content/referencelibrary/GettingStarted/DevelopiOSAppsSwift/PersistData.html


@IBAction func Save(_ sender: Any) {

// self.updateToolbar(id: <#String#>)
addObjective()
// bodyReturn.body = self.text?.text
// bodyReturn.title = self.textfield.text

}


override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//not perimantent
self.text?.layer.borderWidth = 1
self.text?.layer.borderColor = UIColor.red.cgColor
print(selectedKey)
refObjective = Database.database().reference().child("toolbar");

// toolbar.selectedKey = self.transferRow!

// refObjective = Database.database().reference().child("toolbars");

// let bodyFire = refObjective.child("-KwSYtZU_EX1vFFeTI4g").child("body")

print(self.transferRow)

// let bodyFire = self.refObjective.child(transferRow).child("body")
// bodyFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let bodyOnFire = snapshot.value as? String
// self.text?.text = bodyOnFire
//
////
// let titleFire = self.refObjective.child("id").child("title")
// titleFire.observeSingleEvent(of: .value, with: { (snapshot) in
// let titleOnFire = snapshot.value as? String
// self.textfield.text = titleOnFire
//

// })
//This is the key that is desired.


// self.transferRow = WeeklyObjectivesEditorViewController.toolbarList[indexPath.row]
//


}


func addObjective(){
//generating a new key inside artists node
//and also getting the generated key
//let key = refObjective.childByAutoId().key

// let key = refObjective.child("-KwSYtZU_EX1vFFeTI4g").key

//creating artist with the given values
let objective = ["id": self.transferRow,
"body": text?.text! as! String,
"title": textfield.text! as String
] as [String : Any]

//adding the artist inside the generated unique key
refObjective.child(self.transferRow).setValue(objective)

//displaying message



}



// func updateToolbar(id:String){
// //creating artist with the new given values
// let objective = ["id":id,
// "body": text?.text! as! String,
// "title": textfield.text! as! String,
// ]
//
// //updating the artist using the key of the artist
// refObjective.child(id).setValue(objective)
//
// }

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}






}

关于ios - 我如何从某人点击的已创建单元格的 firebase 中提取 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46760766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com