Created
August 12, 2020 16:50
-
-
Save christianselig/3076e6d39f09a1e5e56a05c7e79bef6d to your computer and use it in GitHub Desktop.
An attempt at parsing Reddit using Codable
This file contains hidden or 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
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example JSON (long): http://reddit.com/r/itookapicture.json?raw_json=1