Schaedel420
Schaedel420

Reputation: 175

Trying to erase duplicated values in array retrieved from firebase in swift

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
        
        
      

           }

Upvotes: 0

Views: 321

Answers (1)

Frankenstein
Frankenstein

Reputation: 16341

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.

Upvotes: 1

Related Questions