串接多種 API 製作Lady Gaga App(Twitter篇-Part2-)
Published in
13 min readJun 26, 2020
1.畫面截圖:
2.App操作GIF:
3.GitHub連結:
4.程式解說:
如何取得Twitter的JSON,我之前已經寫過一篇文章,各位讀者可以參考以下這篇
我們先來看看Profile需要哪些項目吧
struct twitterProfileData: Identifiable {
var id: String
var name: String
var screen_name: String
var description: String
var url: String
var friends_count: String
var followers_count: String
var profile_image_url_https: String
var profile_banner_url: String
var display_url:String
var created_at:String
}
比較特別的是額外連結這邊,其實是分成展示的縮網址跟真正的網址,所以我們兩項都要抓
上一篇文章有提到貼心的Postman幫我們把串接的程式碼寫好了,我們來看看修改的成果吧
class gettwitterProfileData: ObservableObject {
@Published var data = [twitterProfileData]()
init(){
var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/users/show.json?screen_name=ladygaga")!,timeoutInterval: Double.infinity)
request.addValue("Bearer AAAAAAAAAAAAAAAAAAAAANVMEwEAAAAAz5uoa0Uq3sPCioWj9Y2QXF1%2BIhY%3D7FaZvITYT2vdNYoZ7dHzYnHuyRJRwtxw6ooDLtzO2ymkBUD2sH", forHTTPHeaderField: "Authorization")
request.addValue("personalization_id=\"v1_lrzacwVLE4YSmOX2j5NL0A==\"; guest_id=v1%3A159118165707713468", forHTTPHeaderField: "Cookie")request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request){(data, _, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
DispatchQueue.main.async {
self.data.append(twitterProfileData())
}
}.resume()
}
}
再把 twitterProfileData 的項目填入,就變成以下完整的Code
class gettwitterProfileData: ObservableObject {
@Published var data = [twitterProfileData]()
init(){
var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/users/show.json?screen_name=ladygaga")!,timeoutInterval: Double.infinity)
request.addValue("Bearer AAAAAAAAAAAAAAAAAAAAANVMEwEAAAAAz5uoa0Uq3sPCioWj9Y2QXF1%2BIhY%3D7FaZvITYT2vdNYoZ7dHzYnHuyRJRwtxw6ooDLtzO2ymkBUD2sH", forHTTPHeaderField: "Authorization")
request.addValue("personalization_id=\"v1_lrzacwVLE4YSmOX2j5NL0A==\"; guest_id=v1%3A159118165707713468", forHTTPHeaderField: "Cookie")request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request){(data, _, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
let dateFormat = DateFormatter()
dateFormat.dateFormat = "於 yyyy年MM月 加入"
let json = try! JSON(data: data!)
let created = json["created_at"].stringValue
let created_at_Date = dateFormatter.date(from: created)
let created_at = dateFormat.string(from: created_at_Date!)
let id = json["id"].stringValue
let name = json["name"].stringValue
let screen_name = json["screen_name"].stringValue
let description = json["description"].stringValue
let url = json["entities"]["url"]["urls"][0]["url"].stringValue
let display_url = json["entities"]["url"]["urls"][0]["display_url"].stringValue
let friends_count = json["friends_count"].stringValue
let followers_count = json["followers_count"].stringValue
var profile_image_url_https = json["profile_image_url_https"].stringValue
profile_image_url_https = profile_image_url_https.replacingOccurrences(of: "_normal", with: "")
let profile_banner_url = json["profile_banner_url"].stringValue
DispatchQueue.main.async {
self.data.append(twitterProfileData(id: id, name: name, screen_name: screen_name, description: description, url: url, friends_count: friends_count, followers_count: followers_count, profile_image_url_https: profile_image_url_https, profile_banner_url: profile_banner_url, display_url: display_url,created_at:created_at))
}
}.resume()
}
}
我用的方法是舊的字典法,透過SwiftyJSON套件,我們可以直接將資料轉成 Dictionary的物件
值得注意的是有關時間的欄位 created_at (創立時間),我們需要先寫好JSON中的DateFormatter()和我們想要的DateFormatter(),然後把String轉成dateFormat,再轉回String
let dateFormatter = DateFormatter()dateFormatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"//JSON中的格式let dateFormat = DateFormatter()dateFormat.dateFormat = "於 yyyy年MM月 加入"//我們想要的格式let created = json["created_at"].stringValuelet created_at_Date = dateFormatter.date(from: created)let created_at = dateFormat.string(from: created_at_Date!)
tweet也是如法炮製一番,列出需要的項目
struct tweetData: Identifiable {
var id: String
var name: String
var url: String
var screen_name: String
var text: String
var retweet_count: String
var favorite_count: String
var profile_image_url_https: String
var created_at:String
}
再利用Postman的幫我們寫的Code串接
class gettweetData: ObservableObject {
@Published var data = [tweetData]()
init(){
var request = URLRequest(url: URL(string: "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=ladygaga&count=30")!,timeoutInterval: Double.infinity)
request.addValue("Bearer AAAAAAAAAAAAAAAAAAAAANVMEwEAAAAAz5uoa0Uq3sPCioWj9Y2QXF1%2BIhY%3D7FaZvITYT2vdNYoZ7dHzYnHuyRJRwtxw6ooDLtzO2ymkBUD2sH", forHTTPHeaderField: "Authorization")
request.addValue("personalization_id=\"v1_lrzacwVLE4YSmOX2j5NL0A==\"; guest_id=v1%3A159118165707713468", forHTTPHeaderField: "Cookie")
request.httpMethod = "GET"
let session = URLSession(configuration: .default)
session.dataTask(with: request){(data, _, err) in
if err != nil{
print((err?.localizedDescription)!)
return
}
let json = try! JSON(data: data!)
let array = json.array!
for i in array {
let id = i["id"].stringValue
let url = i["entities"]["urls"][0]["url"].stringValue
let name = i["user"]["name"].stringValue
let screen_name = i["user"]["screen_name"].stringValue
var text = i["text"].stringValue
text = text.replacingOccurrences(of: url, with: "")
let retweet_count = i["retweet_count"].stringValue
let favorite_count = i["favorite_count"].stringValue
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "E MMM d HH:mm:ss Z yyyy"
let dateFormat = DateFormatter()
dateFormat.dateFormat = "yyyy/MM/dd"
let created = i["created_at"].stringValue
let created_at_Date = dateFormatter.date(from: created)
let created_at = dateFormat.string(from: created_at_Date!)
var profile_image_url_https = i["user"]["profile_image_url_https"].stringValue
profile_image_url_https = profile_image_url_https.replacingOccurrences(of: "_normal", with: "")
DispatchQueue.main.async {
self.data.append(tweetData(id: id,name: name,url: url,screen_name: screen_name, text: text, retweet_count: retweet_count, favorite_count: favorite_count, profile_image_url_https: profile_image_url_https,created_at: created_at))
}
}
}.resume()
}
}
畫面設計就用一張圖來詮釋吧!
想更進一步了解,建議把我的App下載來看