Created
July 26, 2020 20:44
-
-
Save chelseatroy/ef0e0457645dc2eef339a19186bd93a3 to your computer and use it in GitHub Desktop.
Blog Post Service
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
// | |
// BlogPostService.swift | |
// ScottishGaelicTattooHandbook | |
// | |
// Created by Chelsea Troy on 7/26/20. | |
// Copyright © 2020 Chelsea Troy. All rights reserved. | |
// | |
import Foundation | |
enum BlogPostCallingError: Error { | |
case problemGeneratingURL | |
case problemGettingDataFromAPI | |
case problemDecodingData | |
} | |
class BlogPostService { | |
private let urlString = "https://gaelic.co/wp-json/wp/v2/posts?per_page=3" | |
func getBlogPosts(completion: @escaping ([BlogPost]?, Error?) -> ()) { | |
guard let url = URL(string: self.urlString) else { | |
DispatchQueue.main.async { completion(nil, BlogPostCallingError.problemGeneratingURL) } | |
return | |
} | |
let request = URLRequest(url: url) | |
let task = URLSession.shared.dataTask(with: request) { data, response, error in | |
guard let data = data, error == nil else { | |
DispatchQueue.main.async { completion(nil, BlogPostCallingError.problemGettingDataFromAPI) } | |
return | |
} | |
do { | |
let blogPosts = try JSONDecoder().decode([BlogPost].self, from: data) | |
DispatchQueue.main.async { completion(blogPosts, nil) } | |
} catch (let error) { | |
print(error) | |
DispatchQueue.main.async { completion(nil, BlogPostCallingError.problemDecodingData) } | |
} | |
} | |
task.resume() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment