Skip to content

Instantly share code, notes, and snippets.

@yzhong52
Last active February 16, 2020 16:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yzhong52/36f8b7f838be7e2b51295b2b60db31b7 to your computer and use it in GitHub Desktop.
Save yzhong52/36f8b7f838be7e2b51295b2b60db31b7 to your computer and use it in GitHub Desktop.
Building a Client App From Scratch (NewsClient)
// TODO: update the API key
private let apiKey: String = "c8707b3709a34bbe90837f63c71537ed"
private let path: String = "https://newsapi.org/v2/top-headlines?apiKey=\(apiKey)&country=us"
enum ClientError: Error {
case missingResponseData
}
class NewsClient {
func headlines() -> Single<ArticlesResponse> {
return Single.create { (emitter) -> Disposable in
let session = Alamofire.Session()
session.request(path).responseJSON { (response) in
if let error = response.error {
emitter(.error(error))
return
}
guard let data = response.data else {
emitter(.error(ClientError.missingResponseData))
return
}
do {
let articles = try JSONDecoder().decode(
ArticlesResponse.self,
from: data)
emitter(.success(articles))
} catch {
emitter(.error(error))
}
}
return Disposables.create {
session.cancelAllRequests()
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment