测试已测试 | ✓ |
语种语言 | SwiftSwift |
许可证 | MIT |
发布最新发布 | 2017年3月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Andrea Marcolin 维护。
iOS 8.0+ Swift 3.0+
NewsAPIClient 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的Podfile中:
pod "NewsAPIClient"
首先,使用您的NewsAPI.org API密钥创建一个客户端
let client = NewsAPIClient(apiKey: "<YOUR_API_KEY>")
此客户端提供两种方法来交互两个API端点:“/sources”和“/articles”。注意,所有操作都在主线程上执行。强烈建议将每个请求调度到后台队列中,并传递一个完成块,该完成块最终在主线程上根据您的需要进行UI更新。一个通用示例可以在http://stackoverflow.com/questions/24056205/how-to-use-background-thread-in-swift找到
向“/sources”端点发送请求以获取所有来源
client.getSources { (sources, error) in
guard let sources = sources else {
print(error!)
return
}
print(sources)
}
可选地通过类别、语言或国家过滤来源
client.getSources(category: "business",
language: "en",
country: "gb")
{ (sources, error) in
guard let sources = sources else {
print(error!)
return
}
print(sources)
}
通常,将来源请求与向“/sources”端点发送的请求链接起来,以获取特定来源的文章(sortBy是可选的)
client.getSources { (sources, error) in
guard let sources = sources else {
print(error!)
return
}
client.getArticles(sourceId: sources[0].id,
sortBy: sources[0].availableSortBys["latest"]) // if "latest" is not available for this source, defaults to "top"
{ (articles, error) in
guard let articles = articles else {
print(error!)
return
}
print(articles)
}
}
否则,如果您已经有了来源对象(即先前通过来源方法获得),只需将对象传递给getArticles()方法以获取指定的文章。请记住,sortBy是可选的,因此在这种情况下,我们提供了一个不传递sortBy的示例。
client.getArticles(source: source) { (articles, error) in
guard let articles = articles else {
print(error!)
return
}
print(articles)
}
Andrea Marcolin,[email protected]
NewsAPIClient根据MIT许可证提供。有关更多信息,请参阅LICENSE文件。