[TIL] 09.07

Junyoung_Hong·2023년 9월 7일
0

TIL_9월

목록 보기
6/19
post-thumbnail

1. YouTube API 활용하기

현재 진행하고 있는 프로젝트의 메인 기능을 구현하기 위해서는 YouTube API를 사용하는 것이 필수이다.

YouTube API 문서

1-1. Codable을 사용해서 데이터 파싱하기

어떤 API를 사용하던지, 자신의 프로젝트에 맞게 가공을 해서 사용을 해야 한다. 그래서 자신이 사용하려는 API의 문서를 통해, 구조를 파악하는 부분이 중요하다. YouTube API의 구조를 파악한 후, 사용을 하기 위해 Model 폴더로 구분을 하였다.

// 검색 api 사용시 사용되는 구조체
struct SearchItems: Codable {
    let id: VideoInfo
    let snippet: Snippet?
    let statistics: Statistics?
}

이런 구조를 토대로 프로젝트에 사용할 수 있도록 새로운 구조체를 생성했다. 이 부분은 시청기록을 위한 구조체이다.

struct ViewHistory: Codable {
    let viewTime: Date = Date()
    var videoId: String
    var videoThumbnail: String
}

1-2. cell을 동영상 thumbnail로 채우기

이제 사용자가 봤던 영상들을 MyPage의 시청기록 부분에 보여주어야 한다.

  • 우선 기본적인 변수들을 만들어 주었다.
    // API 활용을 위한 변수
    private let apiHandler: APIHandler = APIHandler()
    private let imageLoader: ImageLoader = ImageLoader()
    private var viewHistoryList = UserDataManager.shared.getViewHistory()

1-2-1. TableCell 업데이트 함수 구현

  • ViewHistory를 가져온다.
    func updateUI(items: [ViewHistory]) {
       viewHistoryList = items
       recordCollectionView.reloadData()
    }

1-2-2. CollectionViewCell 업데이트 함수 구현

  • 썸네일의 URL을 가져와서 이미지를 업데이트
    func updateCellImage(viewHistory: ViewHistory) {
       let thumbnailStringURL = viewHistory.videoThumbnail
       guard let url = URL(string: thumbnailStringURL) else { return }
       imageLoader.getImage(url: url) { result in
           switch result {
           case .success(let image):
               DispatchQueue.main.async {
                   self.thumbnailImageView.image = image
               }
           case .failure(let failure):
               print(failure.message)
           }
       }
    }

1-2-3. 각 함수 불러오기

  • ViewController에서 updateUI함수 불러오기
    else if indexPath.row == 1 {
       guard let recordTableViewCell = tableView.dequeueReusableCell(withIdentifier: RecordTableViewCell.identifier, for: indexPath) as? RecordTableViewCell else {
           return UITableViewCell()
       }
       recordTableViewCell.selectionStyle = .none
       recordTableViewCell.recordTableViewCellDelegate = self
       recordTableViewCell.updateUI(items: viewHistoryList)
       return recordTableViewCell
    }
  • TableViewCell에서 updateCellImage함수 불러오기
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
       guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: RecordCollectionViewCell.identifier, for: indexPath) as? RecordCollectionViewCell else { return UICollectionViewCell() }
       guard let viewHistoryList = viewHistoryList, indexPath.row < viewHistoryList.count else { return cell }
               cell.updateCellImage(viewHistory: viewHistoryList[indexPath.row])
       return cell
    }

1-3. 데이터 이동하기

TableViewCell을 눌렀을 때, 데이터가 다른 VC로 이동하게 만들자.

func didTapRecordCollectionViewCell(at indexPath: IndexPath) {
    if indexPath.row < viewHistoryList.count {
        let videoId = viewHistoryList[indexPath.row].videoId
        let videoDetailVC = VideoDetailViewController(videoId: videoId)
        navigationController?.pushViewController(videoDetailVC, animated: true)
    }
}
profile
iOS 개발자를 향해 성장 중

0개의 댓글