0

let db = Firestore.firestore() let user = Auth.auth().currentUser

let tableView = UITableView()
var locationArray = [String]()
var titleArray = [String]() 

override func viewDidLoad() {
    super.viewDidLoad()
    view.backgroundColor = .systemGray6
    tableView.delegate = self
    tableView.dataSource = self
    tableView.backgroundColor = .systemGray6
    navigationController?.navigationBar.isHidden = true
    setupUI()
    fetchFirestoreLocationData()
}

override func viewDidLayoutSubviews() {
    super.viewDidLayoutSubviews()
    tableView.frame.size.height = tableView.contentSize.height
}

func fetchFirestoreLocationData() {
    
    let ref = db.collection("savedPlaces").whereField("userID", isEqualTo: user!.uid)
    
    ref.addSnapshotListener { [weak self] snapshot, error in
        guard let self = self else { return }
        
        if let error = error {
            print(error)
            return
        }
        
        guard let documents = snapshot?.documents else {
            print("no document.")
            return
        }
        
        self.titleArray.removeAll(keepingCapacity: false)
        self.locationArray.removeAll(keepingCapacity: false)
        
        for document in documents {
            if let latitudeStr = document.get("latitude") as? String,
               let longitudeStr = document.get("longitude") as? String,
               let title = document.get("title") as? String {
                
                self.titleArray.append(title)
                self.locationArray.append("\(latitudeStr), \(longitudeStr)")
            }
        }
        print(titleArray)
        self.tableView.reloadData()
    }
}

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell()
    var content = cell.defaultContentConfiguration()
    content.text = titleArray[indexPath.row]
    cell.contentConfiguration = content
    return cell
}

When print command executed, locationArray is not empty but i can't see titles on tableView.

I tried to run function on viewWillAppear and viewDidAppear but result hasn't changed. I pick locations from mapView and save it to firestore, and i want to fetch location data and list locations in tableView.

  • `let tableView = UITableView()`, I haven’t done UIKit development in a long time but that piece of code looks very wrong. Are you using a storyboard or creating your ui in code? – Joakim Danielson Sep 01 '23 at 05:39
  • I'm not using storyboard. Handled them programmatically but i didn't show them in this question. I think the problem is that function must be asynchronous. I'm new and i couldn't find a tutorial about it. – Furkan Kozmaç Sep 01 '23 at 15:34
  • Maybe [this answer](https://stackoverflow.com/a/26277519/9223839) is helpful – Joakim Danielson Sep 01 '23 at 16:22

0 Answers0