Skip to content

Instantly share code, notes, and snippets.

@fumiyasac
Last active July 21, 2018 09:16
Show Gist options
  • Save fumiyasac/412e4f1eab0537d20e94cc129dfd5be4 to your computer and use it in GitHub Desktop.
Save fumiyasac/412e4f1eab0537d20e94cc129dfd5be4 to your computer and use it in GitHub Desktop.
NewYorkTimesのAPIから記事情報を取得する with PromiseKit
import Foundation
import Alamofire
import PromiseKit
import SwiftyJSON
class APIManagerForNewYorkTimes {
private let baseUrl = "https://api.nytimes.com/svc/search/v2/articlesearch.json"
private let key = Constants.NEWYORKTIMES_API_KEY
// MARK: - Singleton Instance
static let shared = APIManagerForNewYorkTimes()
private init() {}
// MARK: - Functions
// NewYorkTimesの最新ニュース一覧を取得する
func getNewsList(page: Int = 0) -> Promise<JSON> {
// APIにリクエストする際に必要なパラメーターを定義する
let parameters: [String : Any] = [
"api-key" : key,
"sort" : "newest",
"id" : "web_url,pub_date,headline,document_type,section_name,byline",
"page" : page
]
// Alamofireの非同期通信をPromiseKitの処理でラッピングする
// 例.
// -----------
// getNewsList(page: 0)
// .done { json in
// // 受け取ったJSONに関する処理をする
// print(json)
// }
// .catch { error in
// // エラーを受け取った際の処理をする
// print(error.localizedDescription)
// }
// -----------
// 参考URL:
// https://medium.com/@guerrix/101-alamofire-promisekit-671436726ff6
return Promise { seal in
Alamofire.request(baseUrl, method: .get, parameters: parameters).validate().responseJSON { response in
switch response.result {
// 成功時の処理(表示に必要な部分だけを抜き出して返す)
case .success(let response):
let res = JSON(response)
let json = res["response"]["docs"]
seal.fulfill(json)
// 失敗時の処理(エラーの結果をそのまま返す)
case .failure(let error):
seal.reject(error)
}
}
}
}
}
class EnglishNews {
// 英語ニュースをページごとに取得する
static func fetchEnglishNewsList(page: Int = 0) {
// 現在の初期設定状態を反映するアクションの実行
APIManagerForNewYorkTimes.shared.getNewsList(page: page)
.done { newsJSON in
print(newsJSON)
// TODO: 完了時の処理
}.catch { error in
print(error)
// TODO: 失敗時の処理
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment