Skip to content

Instantly share code, notes, and snippets.

@christianselig
Created August 12, 2020 16:50
Show Gist options
  • Save christianselig/3076e6d39f09a1e5e56a05c7e79bef6d to your computer and use it in GitHub Desktop.
Save christianselig/3076e6d39f09a1e5e56a05c7e79bef6d to your computer and use it in GitHub Desktop.
An attempt at parsing Reddit using Codable
class RedditManager {
static let shared = RedditManager()
private let session: URLSession
private init() {
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration)
}
func posts(fromSubreddit subreddit: String, completion: @escaping ([RedditPost]?) -> Void) {
let apiURL = URL(string: "https://reddit.com/r/\(subreddit).json?raw_json=1")!
session.dataTask(with: apiURL) { (data, response, error) in
guard let data = data else { return }
do {
let redditPostOuter = try JSONDecoder().decode(RedditPostOuter.self, from: data)
completion(redditPostOuter.posts)
} catch {
print(error)
}
}.resume()
}
}
private struct RedditPostOuter: Decodable {
let data: RedditPostOuterData?
var posts: [RedditPost]? {
return data?.children?.map { $0.data }
}
}
private struct RedditPostOuterData: Decodable {
let children: [RedditPostListingChild]?
}
private struct RedditPostListingChild: Decodable {
let data: RedditPost
}
struct RedditPost: Decodable {
let title: String
let score: Int
}
@christianselig
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment