串接多種 API 製作Lady Gaga App(Reddit篇-Part1-)

1.畫面截圖:

2.Github連結:

3.前言:

最近天氣忽冷忽熱,很容易讓人變得懶惰,而我也在數次上課缺席後,缺交了3份APP作業。

大家或許會覺得我很懶,我是在拖延,但我知道這是能量的累積,在最對的時間點;用最刁鑽的角度;揮出最有力量的一拳。

沒錯,我決定挑戰串接多種API,戰勝那些快要臭掉的Deadline!

4.程式解說:

Peter希望我先做較少人串過的Reddit API,我們就先從他的JSON看起吧!

嗯……似乎沒有這麼直覺,看來我們會需要套件幫忙

透過SwiftyJSON這個套件,串接就容易多了

struct redditData: Identifiable {
var id: String
var title: String
var author: String
var url: String
var imurl: String
var score: String
}

不免俗要先寫好我們需要哪些資料,接下來就開始串接

回頭看JSON資料,很明顯我們要抓的Po文,就在這個children陣列

let json = try! JSON(data: data!)
let children = json["data"]["children"].array!

透過套件,我們可以直接對應data底下的children,藉由 .array 將資料轉成「陣列裡的每個索引都存放著 Dictionary的物件」

而我們需要的資料,例如:title,都在data底下

for i in children{
let id = i["data"]["id"].stringValue
let title = i["data"]["title"].stringValue
let author = i["data"]["author"].stringValue
let url = i["data"]["url"].stringValue
let imurl = i["data"]["thumbnail"].stringValue
let score = i["data"]["score"].stringValue
DispatchQueue.main.async {
self.data.append(redditData(id: id, title: title, author: author, url: url, imurl: imurl,score: score))
}
}

我們就能利用迴圈調列出陣列裡的 Dictionary 值

以下為完整的getData

class getRedditData: ObservableObject {
@Published var data = [redditData]()
init(){
let url = "https://www.reddit.com/r/ladygaga.json"
let session = URLSession(configuration: .default)
session.dataTask(with: URL(string: url)!){(data, _, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
let json = try! JSON(data: data!)
let children = json["data"]["children"].array!
for i in children{
let id = i["data"]["id"].stringValue
let title = i["data"]["title"].stringValue
let author = i["data"]["author"].stringValue
let url = i["data"]["url"].stringValue
let imurl = i["data"]["thumbnail"].stringValue
let score = i["data"]["score"].stringValue
DispatchQueue.main.async {
self.data.append(redditData(id: id, title: title, author: author, url: url, imurl: imurl,score: score))
}
}
}.resume()
}
}

5.結語:

希望這篇文章可以幫助到大家,如果想看我串接其他API,歡迎大家follow我

--

--