SHcommit / LearnMoreSwiftInUdemy

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

[Clone/Instagram] CommentController 채팅 기능 추가 & 개념 정리(UIResponder) #14 - 2

SHcommit opened this issue · comments

채팅 기능 구현

  • 구현 형상

채팅 기능 구현 과정 리뷰

TODO: 상대방 포스트의 하단 comment 클릭시 특정 포스트에 대한 채팅 기능 구현

  • CommentService //Global
  • CommentController //Controller
  • CommentModel //Model
  • CommentViewModelProtocols //ViewModel
  • CommentViewModel //ViewModel
  • InputTextView //VIew
  • CommentInputAccessoryView //View
  • CommentCell //View

1. 채팅 UI

위 사진은 CommentController의 Scene이다.

CommentController를 화면으로 호출하면 tabBar를 숨기고 커스텀 view인 CommentInputAccessoryView가 화면의 하단에 나온다. 이는 사용자의 메시지 입력, Post 전송 두 개의 객체로 구성되어 있다. 사용자가 입력한 텍스트는 CollectionViewFlowLayout으로 구현했다.근데 TableView로 추후 리펙터링할 것이다. cell의 width를 뷰의 크기에 맞춰서 레이아웃 구현해야 하기 때문이다.

2. upload comment, fetch comment

사용자가 텍스트를 입력한 후에 Post버튼을 누르게 되면 CommentInputAccessoryView의 내부 post 프로퍼티의 이벤트 헨들러 함수를 통해 handling했다. 입력한 comment는 파이어베이스에 업로드 후 파이어베이스에서 특정 post의 comment 컬랙션의 문서 추가 후 fetch할 때 파이어베이스 옵저버 함수를 통해 데이터가 추가되었을 때 자동으로 컬랙션 뷰 셀을 갱신한다. 여기서 문제는 데이터를 보낼 때 CommentInputAccessoryView가 UIView인 것이다. CommentController의 navigation을 인스턴스로 갖고 있지 않기 때문에 델리게이트로 CommentController에서 처리하도록 구현했다.

크3

(Firebase data model relation)

크5

파이어베이스에서 여러 컬랙션 중 posts data model entiry는 모든 유저가 올린 post를 저장한다. posts 컬랙션은 여러 개의 문서가 존재한다. 이때 각각의 문서는 사용자가 올린 post정보가 된다.

크6

특정 문서를 클릭하면 필드가 존재한다. 필드에 post 정보가 담긴다. 이 뿐 아니라 comemnts 컬랙션을 추가했다. comments 컬랙션에서는 특정 post에 대해 comment를 날린 user의 문자와 특정 사용자 정보가 저장되어 있다.

크4

맨 처음 CommentController가 초기화 될 때 viewModel에선 fetchComments() 함수를 통해 파이어베이스에서 특정 포스트에 대한 데이터가 추가될 경우 데이터를 받아오는 작업을 observe하도록 설정했다.

위에서 언급한 파이어베이스의 특정 post-> comments에서 사용자의 데이터가 추가될 경우 addSnapshotListener 함수를 통해 fetch를 바로바로 할 수 있다. 파이어베이스에서 지원해주는 함수인데 정말 진짜 신기했다.

크7

초기 viewModel init에서 fetchComments()를 통해 comment 리스트를 받아옴과 동시에 파이어베이스의 addSnapshotListener를 통해 new comment 가 감지 되면 viewModel의 comments 리스트를 업데이트 함과 동시에 newComment publisher에게 input stream을 전송하고 transform(input:) 를 통해 CommentController의 state 중 cell을 갱신한다.

  1. 다이나믹 셀

CommentCell의 label에 대해 commentLabel.numberOfLines = 0으로 함으로써 다이내믹한 height를 설정했다.


새로 알게된 점

UIView타입의 view를 구현하고 auto layout을 지정한 경우 이를 Controller에서 사용할 때 뷰를 추가하면 된다.

새로 공부한 개념

NSMutableAttributedString vs NSAttributedString

이전에도 공부했는데 까먹어서 확실하게 복습했다.