현재 진행하고 있는 프로젝트의 메인 기능을 구현하기 위해서는 YouTube API를 사용하는 것이 필수이다.
어떤 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
}
이제 사용자가 봤던 영상들을 MyPage의 시청기록 부분에 보여주어야 한다.
// API 활용을 위한 변수
private let apiHandler: APIHandler = APIHandler()
private let imageLoader: ImageLoader = ImageLoader()
private var viewHistoryList = UserDataManager.shared.getViewHistory()
func updateUI(items: [ViewHistory]) {
viewHistoryList = items
recordCollectionView.reloadData()
}
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)
}
}
}
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
}
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
}
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)
}
}