#14 模仿 Instagram App (IG), Instagram API , JSON 資料解析篇 #1

剛開始想做照片牆練習就參考數多人的作品,發現有的是將照片放在專案內使用,也有使用輸入網址產生隨機圖片方法。但是我想要能做出來的成品不單調又可以學習到很多,就發現Instagram App 可以學習到網路資料練習、CollectionView照片牆、點選 Button 或水平滑動可切換頁面、點選照片可以顯示po文。

模仿 Instagram App #1

JSON Codable

Decodable : 解碼協議

Encodable : 編碼協議

Coable : 同時遵循 Decodable & Encodable 協議的類型別名。

串接網路上資料最常見的需求是解析JSON 類型的API或檔案,因此解析JSON 中的資料,再轉化成我們自訂型別資料使用。

Instagram API

將以下的username替換成欲搜尋的帳號名稱,即可以得到該帳號首頁的JSON資料。

https://www.instagram.com/username/?__a=1

取得 ㄇㄚˊ幾兔官方帳號(machiko324)首頁的 JSON 資料。

https://www.instagram.com/machiko324/?__a=1

使用 Postman,取得 ㄇㄚˊ幾兔 Instagram 首頁的 JSON 資料。
(也可使用Web Browser 直接取得 Instagram 首頁的 JSON 資料)

https://www.postman.com/
Postman 取得 ㄇㄚˊ幾兔 Instagram 首頁的 JSON 資料

JSON 資料若覺得雜亂,可以使用 JSON Editor Online 方便檢視資料

https://jsoneditoronline.org
JSON Editor Online

發現 Instagram API JSON 資料多到爆炸,花不少時間尋找需要的JSON資料如下所示

使用者帳號 : username 
使用者名稱 : fullname
自我介紹 : biography
總貼文數 : edge_owner_to_timeline_media >> count
粉絲人數 : edge_followed_by >> count
追蹤者數量 : edge_follow >> count
頭像 : profile_pic_url / profile_pic_url_hd
圖片貼文資料 : edge_owner_to_timeline_media (只取得12筆資料)
圖片貼文標題 :
edge_owner_to_timeline_media >> edges >> edge_media_to_caption
圖片貼文按讚數 : edge_liked_by
圖片貼文留言數 :
edge_owner_to_timeline_media >> edges >> edge_media_to_comment
圖片貼文時間 :
edge_owner_to_timeline_media >> edges >> taken_at_timestamp
影片貼文資料 : edge_felix_video_timeline
被標記文章 : 沒發現

自訂型別 InstagramResponse

解析JSON 中的資料,再轉化成我們自訂型別資料使用

URLSession 抓取資料

寫一個 func fetchInstagramData() 做URLSession來抓取資料。
因URLSession 是在 background thread,抓取資料後要透過DispatchQueue.main.async 切換到 main thread 來畫面UI元件更新。
(這裡寫的 collatingOfData()做暫時整理資料並更新畫面 UI元件)

下一篇

Reference:

--

--