본문 바로가기
TIL

250507 TIL | FireStore 사용법 익히기, 딕셔너리 활용

by 23g 2025. 5. 7.

안녕하세요 ~

오늘은 어제 공부한 코드를 안보고 혼자서 쳐봤어요!

 

Flash Chat 앱 처음부터 끝까지 논스톱으로 작성해봄!

-> 총 3시간 정도 걸림 ㅎ

 

다만,, 복습하기로 체크해 놓은 부분은 약간의 컨닝이 있었기 때문에,,,

다시 복습하는걸로!!!

import FirebaseFirestore
import FirebaseCore
import FirebaseAuth

import UIKit

class ChatViewController: UIViewController {
  
  @IBOutlet weak var tableView: UITableView!
  @IBOutlet weak var messageTextfield: UITextField!
  
  private var messages: [Message] = []
  
  let db = Firestore.firestore()
  
  
  override func viewDidLoad() {
    super.viewDidLoad()
    self.navigationItem.hidesBackButton = true
    self.title = "Flash chat"
    self.tableView.dataSource = self
    //self.tableView.delegate = self
    self.tableView.register(
      UINib(nibName: K.cellNibName, bundle: nil),
      forCellReuseIdentifier: K.cellIdentifier)
    self.loadMessages()
  }
  
  
  // 복습하기 ⭐️
  @IBAction func logout(_ sender: UIBarButtonItem) {
    do { 
      try Auth.auth().signOut()
      // ⭐️ popToRootViewController 함수를 까먹음
      self.navigationController?.popToRootViewController(animated: true)
    } catch let error as NSError {
      print(error)
    }
  }
  
  // 복습하기 ⭐️
  @IBAction func sendPressed(_ sender: UIButton) {
  // ⭐️ currentUser에서 email로 한단계 더 들어가야 함!
    guard let sender = Auth.auth().currentUser?.email else { return }
    guard let body = self.messageTextfield.text else { return }
    guard body.isEmpty == false else { return }
    
    // ⭐️ data 구조로 Document 올리는 방법 기억하기
    db.collection(K.FStore.collectionName).addDocument(data: [
      K.FStore.senderField: sender,
      K.FStore.bodyField: body
    ])
  }
  
  // 복습하기 ⭐️
  func loadMessages() {
    db.collection(K.FStore.collectionName).getDocuments { querySnapShot, error in
      guard let snapShotData = querySnapShot?.documents else { return }
      for document in snapShotData {
        let doc = document.data()
        // ⭐️ 딕셔너리 타입 사용 방법 익히기
        if let sender = doc["sender"] as? String ,
           let body = doc["body"] as? String {
          let message = Message(sender: sender, body: body)
          self.messages.append(message)
        }
      }
      DispatchQueue.main.async {
        self.tableView.reloadData()
      }
    }
  }
  
  
}

extension ChatViewController: UITableViewDataSource {
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.messages.count
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    guard let cell = self.tableView.dequeueReusableCell(
      withIdentifier: K.cellIdentifier,
      for: indexPath) as? MessageCell else { return UITableViewCell()}
      // ⭐️ 복습하기
      // ⭐️ indexPath.row 사용 방법! & body로 한 단계 더 들어가야함!
    cell.label.text = self.messages[indexPath.row].body
    return cell
  }
  
  
}

 

체크해야할 부분도 주석으로 메모 완~

 

오늘 오랜만에 출근하니까 너무 힘들었어요 흑흑

하지만 퇴근하자마자 밥 먹고 공부 달리기 성공 잘해따잉

굿~ 앙뇽