Last active
April 4, 2018 12:01
-
-
Save tsif/95cbca5d75a4352c85a7a2b870fd3221 to your computer and use it in GitHub Desktop.
Search for a list of itunes tracks and put the results into a collection of Codables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//: Playground - noun: a place where people can play | |
import UIKit | |
import Foundation | |
import PlaygroundSupport | |
// so we can run asynchronous code in a playground | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
let iso8601Full: DateFormatter = | |
{ | |
let formatter = DateFormatter() | |
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" | |
formatter.calendar = Calendar(identifier: .iso8601) | |
formatter.timeZone = TimeZone(secondsFromGMT: 0) | |
formatter.locale = Locale(identifier: "en_US_POSIX") | |
return formatter | |
}() | |
let decoder = JSONDecoder() | |
decoder.dateDecodingStrategy = .formatted(iso8601Full) | |
struct iTunesTrackList: Codable | |
{ | |
private enum CodingKeys : String, CodingKey | |
{ | |
case count = "resultCount" | |
case tracks = "results" | |
} | |
let count : UInt64 | |
let tracks : [iTunesTrack] | |
} | |
struct iTunesTrack: Codable, CustomStringConvertible | |
{ | |
let artistName : String | |
let trackName : String | |
let releaseDate: Date | |
var description: String | |
{ | |
return "\(artistName) - \(trackName) - \(releaseDate)" | |
} | |
} | |
let url = URL(string: "https://itunes.apple.com/search?media=music&entity=musicTrack&term=beatles&limit=10") | |
let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in | |
guard let data = data else | |
{ | |
return | |
} | |
if let list = try? decoder.decode(iTunesTrackList.self, from: data) | |
{ | |
list.tracks.forEach({ (track) in | |
print(track) | |
}) | |
} | |
else | |
{ | |
print("No tracks") | |
} | |
} | |
task.resume() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment