iTunes API 抓取(JSON)
以 iTunes 搜尋 swift 當例子
API 的網址為:
https://itunes.apple.com/search?term=swift&media=music&country=tw
可以用 JSON Editor online 看一下內容。
解析時要一層一層的解
先用playground測試
這是第一層:
解析:
struct SearchResponse: Codable {
let resultCount: Int
let results: []
}
results :[] 因為還不知道 array 成員的型別,所以先寫 [ ]。
這是第二層:
定義型別: StoreItem
解析:
struct StoreItem: Codable {
let trackId: Int
let artistName: String
let trackName: String
let collectionName: String?
let previewUrl: URL
let artworkUrl100: URL
let trackPrice: Double?
let isStreamable: Bool?
}
然後 results :[]
改成 results: [StoreItem]
程式碼:
struct SearchResponse: Codable {
let resultCount: Int
let results: [StoreItem]
}
struct StoreItem: Codable {
let trackId: Int
let artistName: String
let trackName: String
let collectionName: String?
let previewUrl: URL
let artworkUrl100: URL
let trackPrice: Double?
let isStreamable: Bool?
}
第二種寫法
SearchResponse 包住 StoreItem
struct SearchResponse: Codable {
let resultCount: Int
let results: [StoreItem]
struct StoreItem: Codable {
let trackId: Int
let artistName: String
let trackName: String
let collectionName: String?
let previewUrl: URL
let artworkUrl100: URL
let trackPrice: Double?
let isStreamable: Bool?
}
}
注意
有些 property 被宣告為 optional
因為 JSON 裡有些 key 不會每一筆資料都有
比方不是每首歌都可以買,所以不一定有 trackPrice
不一定會有的 collectionName,trackPrice & isStreamable 設為 optional
如果沒有設為 optional,到時候一旦發現沒有這些欄位,將造成轉換失敗。
測試 JSON 解碼是否成功
方法 1: 使用 async & await
let urlString = "https://itunes.apple.com/search?term=swift&media=music&country=tw"
if let url = URL(string: urlString) {
Task {
do {
let (data, _) = try await URLSession.shared.data(from: url)
let decoder = JSONDecoder()
let searchResponse = try decoder.decode(SearchResponse.self, from: data)
print(searchResponse.results)
} catch {
print(error)
}
}
}
方法 2: 使用 completion handler
let urlString = "https://itunes.apple.com/search?term=swift&media=music&country=tw"
if let url = URL(string: urlString) {
URLSession.shared.dataTask(with: url){
data, response, error
in
if let data {
let decoder = JSONDecoder()
do {
let searchResponse = try decoder.decode(SearchResponse.self, from: data)
} catch {
print(error)
}
}
}.resume()
}
中文搜尋會不一樣
需要加上一段程式碼:
.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
完整程式碼:
if let urlString = "https://itunes.apple.com/search?term=伍佰&media=music&country=tw".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed),
let url = URL(string: urlString){
URLSession.shared.dataTask(with: url){
data, response, error
in
if let data {
let decoder = JSONDecoder()
do {
let searchResponse = try decoder.decode(SearchResponse.self, from: data)
let itme = searchResponse.results[1]
print(itme.trackName, itme.previewUrl)
} catch {
print(error)
}
}
}.resume()
}
練習檔案
0927jsonDemoiTunesPG.zip