今日Code打。iOS常見的列表應用<TableView, CollectionView>。使用 Google YoutubeDataAPI取得指定播放清單

K's 生活Quota。打Code人生
5 min readApr 26, 2021

--

專案採用MVVM架構

💡應用目標

  1. 使用自訂Cell.xib製作Cell UI
  2. 取得網路資料應用及JSON 解碼轉成自訂Model
  3. 取回API資料設定到列表上
  4. Fetch更多資料

📂檔案標的

使用自訂Cell.xib製作Cell UI

  1. 新增cell.swift 及cell.xib檔案(File > New > File,shortCut: cmd + N)
  2. 選擇Cocoa Touch Class > Next
  3. Class: Cell命名、 Subclass of: UITableViewCell、 勾選Also create XIB file
  4. 於Cell裡設定UI
  5. 設定Table View Cell — identifier

取得網路資料應用JSON 解碼成自訂Model

  1. 應用Google YouTube Data API (文件請參考下方連結)

2. 申請Google API Key (專案內API Key請自行更換)

3. 建立Data Model (搭配Postman及API文件)

YoutubeData.swift

4. 建立API請求

  • 依播放清單為例,取得清單內影片ID
  • 依影片ID取得影片細節
APIRequestHelper.swift

於ViewModel建立呼叫API取資料的方法

YoutubeListViewModel.swift

取回API資料設定到列表上

  • 14行建立ViewController對應ViewModel
  • 於viewDidLoad()時呼叫setupTableView()、bindData()
  • 25–29將Cell與TableView綁定、設定TableViewDataSource及Delegate,最後設定FooterView
  • 37–43呼叫viewModel.fetchData()用來執行API請求
  • 47–61設定tableViewDataSource,提供資料數量、提供資料給Cell綁定
  • 64–69設定tableViewDelegate,當點擊Cell時,將media組成影片網址,透過SafariViewController開啟網頁
YoutubeListViewController.swift

Fetch更多資料

參考YoutubeListViewController,52–61行。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {    guard let cell = tableView.dequeueReusableCell(withIdentifier:  "\(YoutubeDataCell.classForCoder())", for: indexPath) as?  YoutubeDataCell, viewModel.medias.count > 0 else { return UITableViewCell() }    // 當indexPath.row == 當前資料筆數-2時,繼續抓取新資料    let data = viewModel.medias[indexPath.row]    if indexPath.row == viewModel.medias.count - 2 {        reloadData()    }    cell.setupCell(item: data)    return cell}

這邊省略Cell設定資料,歡迎下載SourceCode

看更多

--

--