NewsAPI
示例
要运行示例项目,请克隆仓库,然后首先从 Example 目录运行 pod install
。
使用
初始化
首先用您的 API 密钥进行设置。
let news: News = News(apiKey: "your-api-key")
获取头条新闻
返回一个国家或类别的突发新闻头条,或当前正在单一或多源上运行。
let options: [QueryOptions] = [
.country(.us),
.pageSize(5),
.sortBy(.popularity)
]
news.get(.topHeadlines, with: options, headlinesCompletion: { [weak self] (headlines, error) in
if let headlines = headlines, let articles = headlines.articles {
debugPrint(articles)
}
})
获取所有内容
NewsAPI 黄页索引了超过 50,000 家大小新闻和博客文章的发布来源,您可以通过此端点进行搜索。
let options: [QueryOptions] = [
.domains(["bbc.co.uk", "bbc.com"]),
.excludeDomains(["google.com"]),
.country(.us)
]
news.get(.everything, with: options, headlinesCompletion: { [weak self] (headlines, error) in
if let headlines = headlines, let articles = headlines.articles {
debugPrint(articles)
}
})
获取来源
返回 NewsAPI 黄页索引的知名来源的信息(包括名称、描述和类别)。
let options: [QueryOptions] = [
.language(.en),
.category(.technology),
.country(.us)
]
news.get(.sources, with: options, sourcesCompletion: { [weak self] (sources, error) in
if let sources = sources {
debugPrint(sources)
}
})
查询选项
可用于过滤结果的查询选项。
/// Keywords or a phrase to search for.
case query(String)
/// Keywords or phrases to search for in the article title only.
case titleQuery(String)
/// The news sources or blogs you want headlines from.
case sources([String])
/// Domains (eg bbc.co.uk, techcrunch.com, engadget.com) to restrict the search to.
case domains([String])
/// Domains (eg bbc.co.uk, techcrunch.com, engadget.com) to remove from the results.
case excludeDomains([String])
/// A date and optional time for the oldest article allowed.
case fromDate(Date)
/// A date and optional time for the newest article allowed.
case toDate(Date)
/// Code of the language you want to get headlines for.
case language(Language)
/// The order to sort the articles in.
case sortBy(SortOptions)
/// The category you want to get headlines for.
case category(Category)
/// The code of the country you want to get headlines for.
case country(Country)
/// The number of results to return per page (request). 20 is the default, 100 is the maximum.
case pageSize(Int)
/// Use this to page through the results if the total results found is greater than the page size.
case page(Int)
安装
NewsAPI 通过 CocoaPods 提供。要安装它,只需将以下行添加到您的 Podfile
pod 'NewsAPI'
作者
imryan, [email protected]
许可
NewsAPI 在 MIT 许可证下提供。有关更多信息,请参阅 LICENSE 文件。