2017-10-15 9 views
0

Comment extraire la clé de la base de données d'une cellule déjà créée (j'utilise TableView) sur laquelle quelqu'un a tapé, et créer cela comme Var local? Je veux le savoir afin que je puisse transférer la clé dans la vue suivante afin que je puisse faire un storyboard générique mais les champs de texte changent avec la clé. Cela signifie également que je veux définir les données dans un contrôleur de vue puis l'envoyer à un autre qui, si j'utilise la même base de données (je suis) pour cela, j'aurais besoin d'être édité sur le second contrôleur de vue.Comment extraire la clé de la base de données d'une cellule déjà créée sur laquelle quelqu'un a tapé

J'ai déjà autant sur le deuxième contrôleur de vue (pour firebase)

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

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

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

     }) 

et la vue tout le premier/contrôleur tableview

 // 
// 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 label: UILabel! 
    @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! 
    //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() 
     restructureDBKeys() 
     //reloading the tableview 
     self.tableViewToolbar.reloadData() 
    } 

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

    // print(self.selectedKey + "this is the key working ------ ___- -----") 
     //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") 

     // 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 


        } 
       } 
      } 
     }) 


     //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"] 
//     let toolbarSelectedKey = toolbarObject?["selectedKey"] 
//// 
//     creating artist object with model and fetched values 
//     //let toolbar = ToolbarModel(toolbar1: "String?") 

        //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() 
      } 
     }) 
     // 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 = refToolbars.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 
     refToolbars.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 
// 
//  } 
// } 
    //list to store all the artist 
// var toolbarList = [ToolbarModel]() 

    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 
    // let toolbar: ToolbarModel 

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

     selectedKey = (arrayOfIDs[indexPath.row] as? String)! 
     //selectedKey = toolbar.selectedKey 
     print(selectedKey + "this is the selected [email protected] selected") 
     print(dataPassedMedium + "this is the dataPassedMedium [email protected] 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 
//  let myVC = storyboard?.instantiateViewController(withIdentifier: "AddNewObjectiveViewController") as! AddNewObjectiveViewController 
//  myVC.transferRow = selectedKey 
//  navigationController?.pushViewController(myVC, animated: true) 

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

    } 






//  func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { 
//   if segue.identifier == "weeklyadd" { 
//    if let DVC = segue.destination as? AddNewObjectiveViewController{ 
//     DVC.transferRow = selectedKey 
//     print("data should be transfered") 
//    } else { 
//     print("Data NOT Passed! destination vc is not set to firstVC") 
//    } 
//   } else { print("Id doesnt match with Storyboard segue Id") } 
//  } 
// 

} 
var dataPassedMedium: String! 

et la vue tout le deuxième contrôleur

+0

Vous voulez essentiellement pour obtenir le 'childByAutoId()'? – Torewin

Répondre

0

Pour regrouper les clés à utiliser dans un tableView, vous pouvez utiliser un dictionary ou un array - votre préférence.

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

En didSelectRowAt sera lorsque vous sélectionnez la clé:

let selectedKey = arrayOfIDs[indexPath.row] as? String

// 
// 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. 
    } 






} 
+0

Les commentaires ne sont pas pour une discussion prolongée; cette conversation a été [déplacé pour discuter] (http://chat.stackoverflow.com/rooms/157091/discussion-on-answer-by-torewin-how-would-i-pull-the-key-from-firebase- de-un-alr). – Andy