#145 利用 API 回傳的 JSON 輸入 array 的假資料

以 IG API 為例,利用 API 回傳的 JSON 輸入 array 的假資料,將 array 的每一筆資料顯示在 table view 或 collection view。

抓取 API 回傳的 JSON 資料

以下範例抓取 Apple IG 的資料,網址如下。

https://www.instagram.com/apple/?__a=1&__d=dis

利用 JSON Editor Online 排版美美的 JSON 資料

為了方便閱讀 JSON 資料,我們利用 JSON Editor Online 排版美美的 JSON 資料。

研究 JSON,手動輸入假資料

定義 IG 的資料型別 Post,在 static computed property data 裡輸入 array 資料。值得注意的,圖片網址會過期,所以只有當下可以測試,過一段時間後會抓不到圖片。

struct Post {
let caption: String
let imageURL: String
let likeCount: Int
}
extension Post {

static var data: [Self] {

[
Post(caption: "“My wife found this baby snail while we were picking apples in our garden. Because of its tiny size, using the 2x lens was the only way to take the photo—I held the apple in one hand and raised it a little in order to use the sunset as background.” #ShotoniPhone by Özgür B. @ozgurbilge", imageURL: "https://instagram.fkhh1-2.fna.fbcdn.net/v/t51.2885-15/e35/p1080x1080/170171225_495703725138717_886929452029924285_n.jpg?tp=1&_nc_ht=instagram.fkhh1-2.fna.fbcdn.net&_nc_cat=1&_nc_ohc=WUBAiZo9VF0AX_HWOtV&edm=ABfd0MgAAAAA&ccb=7-4&oh=d17236128757f8da8cdcd7759280db97&oe=6093DB7C&_nc_sid=7bff83", likeCount: 69473),

Post(caption: "Commissioned by Apple. “I want to see a joyful piece with black men in it because we’re seeing way too much pain in the media and the news. I wanted to create something that would be a much-needed pause from everything that’s happening. I want joy.” #ShotoniPhone by Ciara Z. @ciara.zo, Student.", imageURL: "https://instagram.fkhh1-1.fna.fbcdn.net/v/t51.2885-15/e35/142268701_1049850905520842_1530011004850814938_n.jpg?tp=1&_nc_ht=instagram.fkhh1-1.fna.fbcdn.net&_nc_cat=102&_nc_ohc=YZihg_kgnhQAX9uFt6n&edm=ABfd0MgAAAAA&ccb=7-4&oh=e2f963bab9f43ed81015fd27dbcf4c6d&oe=6070C165&_nc_sid=7bff83", likeCount: 70559)
]
}
}

對 computed property 不熟悉的朋友,可參考以下連結的說明。

在 table view controller 宣告儲存 array 資料的 property

將 posts 的內容設為 Post.data。

class PostsTableViewController: UITableViewController {

let posts = Post.data

使用抓圖套件 Kingfisher 顯示網路圖片

import Kingfisher,然後利用 image view 的 kf.setImage 設定圖片。

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

guard let cell = tableView.dequeueReusableCell(withIdentifier: "\(PostTableViewCell.self)", for: indexPath) as? PostTableViewCell else { return UITableViewCell() }

let post = posts[indexPath.row]
cell.photoImageView.kf.setImage(with: url)

return cell
}

Demo 畫面

基本版: 固定高度的照片

進階版: 依據照片比例自動調整高度

IG API 的 JSON 資料裡包含圖片的寬高資訊。

作品集

--

--

彼得潘的 iOS App Neverland
彼得潘的 100 道 Swift iOS App 謎題

彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,彼得潘的 Swift 程式設計入門,App程式設計入門作者,http://apppeterpan.strikingly.com