Published in
4 min readSep 19, 2022
[作業]回傳 JSON 格式資料的有趣第三方 API,讀取資料做一個 App:有貓膩
import UIKit
import Kingfisher
private let reuseIdentifier = "CatCollectionViewCell"class CatCollectionViewController: UICollectionViewController {
var cats: [Cat] = []
override func viewDidLoad() {
super.viewDidLoad()
var request = URLRequest(url: URL(string: "https://api.thecatapi.com/v1/Favourites")!, cachePolicy: .returnCacheDataElseLoad, timeoutInterval: 3)
request.setValue("DEMO-API-KEY", forHTTPHeaderField: "x-api-key")
URLSession.shared.dataTask(with: request) { data, response, error in
if let data, let response = response as? HTTPURLResponse, response.statusCode == 200, error == nil {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
do {
let catResponse = try decoder.decode([Cat].self, from: data)
DispatchQueue.main.async {
self.cats = catResponse
self.collectionView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of items
return cats.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CatCollectionViewCell
let cat = cats[indexPath.item]
cell.catImageView.kf.setImage(with: cat.image.url)
return cell
}
}