Skip to content

Instantly share code, notes, and snippets.

@rtking1993
Created April 8, 2018 12:39
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Remote class that allows us to connect to NYT articles API
// MARK: Frameworks
import Foundation
// MARK: ArticleRemote
class ArticleRemote {
static func retrieveArticles(completion: @escaping(_ articles: Articles) -> Void) {
let session = URLSession(configuration: .default)
let apiURL: URL = URL(string: "https://api.nytimes.com/svc/mostpopular/v2/mostviewed/Technology/1.json")!
var request: URLRequest = URLRequest(url: apiURL)
request.addValue("245f0d40c8d64f07bfe69265569e34a9", forHTTPHeaderField: "api-key")
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil, let data = data else {
return
}
let decoder = JSONDecoder()
do {
let articles = try decoder.decode(Articles.self, from: data)
completion(articles)
} catch let error {
print("Error: \(error)")
}
}
task.resume()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment