0

I am trying to retrieve the value called memberJobfrom a firebase dict. After I retrieved it, the goal is to erase the duplicates, showing the unique values in a TableView. The problem is that jobsis empty but memberJobactually has the values while looping over.

Maybe someone can help me! :)

import UIKit
import FirebaseDatabase
import Foundation
import FirebaseFirestoreSwift
import CodableFirebase

class ProjectCharacterViewController: UIViewController {
    
    
    
// MARK: - Properties
    
   
    @IBOutlet weak var specTxt: UITextField!
    @IBOutlet weak var difficultyTxt: UITextField!
    @IBOutlet weak var budgetTxt: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    var member = [TeamMember]()
    var jobs: [String] = []
    var uniqueJobs = [MemberJobsStruct]()
    var soloJobs: [String] = []
    var singleJobs: [String] = []

    
    var test =  ["Hallo", "Birne", "Apfel"]
    
    
     
    

    override func viewDidLoad() {
        super.viewDidLoad()
        
        getJobs(for: User.current) { (memberJob) in
            self.uniqueJobs = memberJob
        }
        
        soloJobs = removeDuplicates(array: jobs)
        print("SoloJobs :", soloJobs)
        
        DispatchQueue.main.async {
               self.tableView.reloadData()
                   }

        
    
    }

    

// MARK: - Functions
    
    
    func gettheJob() {
              soloJobs = removeDuplicates(array: jobs)
          
          print("These are the unique Jobs: ", soloJobs)
        
       
      }
      
    
    func getJobs(for user: User, completion: @escaping ([MemberJobsStruct]) -> Void) {
        
         
         let ref = Database.database().reference().child("team").child(user.uid)
         
         
                 ref.observe(DataEventType.value, with: { snapshot in
                    for case let child as DataSnapshot in snapshot.children {
                    guard let value = child.value as? [String: Any] else {
                        return completion ([])
                        
                }
                        let memberJob = value["memberJob"] as! String
                        self.jobs.append(memberJob)
                        
                       
                    }
                 })
           }
    
  
func removeDuplicates(array: [String]) -> [String] {
    var encountered = Set<String>()
    var result: [String] = []
    for value in array {
        if encountered.contains(value) {
            // Do not add a duplicate element.
        }
        else {
            // Add value to the set.
            encountered.insert(value)
            // ... Append the value.
            result.append(value)
        }
    }
    return result
    }
}

// MARK: - UITableViewDataSource

extension ProjectCharacterViewController: UITableViewDataSource {

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
      
//            let job = jobs[indexPath.row]
            let cell = tableView.dequeueReusableCell(withIdentifier: "ProjectCharacterTableViewCell") as! ProjectCharacterTableViewCell
        cell.jobLabel.text = soloJobs[indexPath.row]
            return cell
        }
    }


// MARK: - UITableViewDelegate

extension ProjectCharacterViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
     return 60
    }
}

Update: I tried to simply make a new array soloJobsout of jobsbut even this is not working. what is the right approach to do something like this? right now I tried it several ways including this one but nothings working...

  func getJobs(for user: User, completion: @escaping ([MemberJobsStruct]) -> Void) {
        
         var jobs: [String] = []

         let ref = Database.database().reference().child("team").child(user.uid)
        
                 ref.observe(DataEventType.value, with: { snapshot in

                    for case let child as DataSnapshot in snapshot.children {
                    guard let value = child.value as? [String: Any] else {
                        return completion ([])
                        
                }
                        let memberJob = value["memberJob"] as! String
                        jobs.append(memberJob)
                        DispatchQueue.main.async {
                                   self.tableView.reloadData()
                               }
                    }
                 })
            soloJobs = jobs
        
        
      

           }

Schaedel420
  • 175
  • 11
  • where are you use `removeDuplicates`? – RrrangeTop Jul 21 '20 at 12:55
  • Not yet... since the array itself is still empty. The function is working. I just need to get the job array – Schaedel420 Jul 21 '20 at 13:07
  • If you don't want duplicates in the database the more efficient way is to check for duplicates **before adding** a record. – vadian Jul 21 '20 at 17:30
  • no no the duplicates are highly needed!! its just that in this vc i want people to choose the quantity of jobs needed. The jobs are getting fetched by the different Team Member profiles. But if there are three Cameraman for example, its obvious that 1x cameraman is enough to show and therefore to choose the quantity – Schaedel420 Jul 21 '20 at 17:33

1 Answers1

1

You're probably just missing the part where you should reload the UITableView after the getJobs method has appended the jobs.

func getJobs(for user: User, completion: @escaping ([MemberJobsStruct]) -> Void) {
    //...
    ref.observe(DataEventType.value, with: { snapshot in
        for case let child as DataSnapshot in snapshot.children {
            //...
        }
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    })
}

Update: For getting the Unique objects from an array using the extension method from here.

Frankenstein
  • 15,732
  • 4
  • 22
  • 47
  • Thanks for that! It actually worked buuuuut right now I wanted to actually deleted the duplicates and store the unique variables in a new array called ````soloJobs````and therefore let those only be showed in the tableview. But actually it's not working. I modified my Code in the question to the new one? Any other help again? :) – Schaedel420 Jul 21 '20 at 17:21
  • Check the update that I've posted above for removing duplicates from an array. Use it and you'll get your result. – Frankenstein Jul 21 '20 at 17:28
  • its weird i just don't get it. Why can't I even make a new array called ````soloJobs```` out of ````jobs```` without even deleting duplicated values? iI tried almost every possibility... right now in the updated area of my question this is my approach but yeah nothing works... – Schaedel420 Jul 21 '20 at 18:59