#15 — 串接Instagram API ,模仿製作 IG 使用者畫面

呈現畫面:

原本是想製作播放影片而不是圖片,但由於某些因素(太菜),所以只擺了圖片,但之後會再更新用成影片。

做法其實大部分跟Dcard大同小異,差別在於第一頁是用CollectionView去製作,而使用者資訊利用了Collection Reusable View,類似於製作Table View Header,還有最重要的讓照片呈現螢幕寬的三分之一。

  • 公開帳號的API網址(抓取自己喜歡的公開帳號)
https://www.instagram.com/公開帳號的id/?__a=1

自定義的資料型別

struct InstagramResponse:Codable{
let graphql:Graphql
struct Graphql:Codable{
let user:User
struct User:Codable{
let biography:String //自我介紹
let external_url:String //fox網站自介連結
let edge_followed_by:Edge_followed_by //被追蹤人數
struct Edge_followed_by:Codable{
let count:Int
}
let edge_follow:Edge_follow //追蹤人數
struct Edge_follow:Codable{
let count:Int
}
let full_name:String //名字
let profile_pic_url:URL //頭像
let username:String //帳號
let edge_owner_to_timeline_media:Edge_owner_to_timeline_media
struct Edge_owner_to_timeline_media:Codable {
let count:Int //總貼文數
let edges:[Edges]
struct Edges:Codable {
let node:Node
struct Node:Codable{
let display_url:URL //貼文圖片url
let video_url:URL //貼文影片url
let video_view_count:Int //影片觀賞人數
let edge_media_to_caption:Edge_media_to_caption //貼文文字
struct Edge_media_to_caption:Codable {
let edges:[Edges]
struct Edges:Codable {
let node:Node
struct Node:Codable {
let text:String
}
}
}
let edge_media_to_comment:Edge_media_to_comment //留言數量
struct Edge_media_to_comment:Codable {
let count:Int
}
let edge_liked_by:Edge_liked_by //貼文按讚數
struct Edge_liked_by:Codable {
let count:Int
}
let taken_at_timestamp: Date
}
}
}
}
}
}

將解析JSON的Decoder寫在自定義的Function裡

var userInfo:InstagramResponse?var postImages = [InstagramResponse.Graphql.User.Edge_owner_to_timeline_media.Edges]()func fetchItem(){
let urlString = "https://www.instagram.com/thesimpsons/?__a=1"
if let url = URL(string: urlString){
URLSession.shared.dataTask(with: url) { data, response, error in
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
if let data = data {
do {
let instagramResponse = try decoder.decode(InstagramResponse.self, from: data)
self.userInfo = instagramResponse
self.postImages = instagramResponse.graphql.user.edge_owner_to_timeline_media.edges
DispatchQueue.main.async {
self.collectionView.reloadData()
}
} catch {
print(error)
}
}
}.resume()
}
}

由於下半部分只需要顯示圖片,所以只需將自定義的Collection View Cell加入Image View並設定等同於cell大小即可。

再來就是模擬IG設定一行有三張照片,由於機型寬度都各不相同,所以這裡利用collectionView.bounds.width去做計算。

(如果是用view controller + collection view 做的話,要改成let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout而寬度可以用UIScreen.main.bounds.width

實作Collection View DataSource、Collection View Delegate

而特別是Collection Reusable View,將需要顯示的元件拉好在自定義的文件裡,在定義 collectionView(_:viewForSupplementaryElementOfKind:at:),在 function 裡產生 header view 回傳。

點選圖片cell會觸發segue並傳直到下一個頁面

--

--