{"id":13872192,"url":"https://github.com/Raureif/WikipediaKit","last_synced_at":"2025-07-16T02:30:28.476Z","repository":{"id":37251713,"uuid":"91013527","full_name":"Raureif/WikipediaKit","owner":"Raureif","description":"Wikipedia API Client Framework for Swift on macOS, iOS, watchOS, and tvOS","archived":true,"fork":false,"pushed_at":"2023-08-27T10:39:30.000Z","size":144,"stargazers_count":341,"open_issues_count":3,"forks_count":29,"subscribers_count":7,"default_branch":"main","last_synced_at":"2024-10-29T08:37:46.279Z","etag":null,"topics":["ios","macos","swift","swift3","tvos","watchos","wikipedia","wikipedia-api"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Raureif.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null}},"created_at":"2017-05-11T18:55:41.000Z","updated_at":"2024-08-30T22:06:00.000Z","dependencies_parsed_at":"2024-01-16T10:09:26.854Z","dependency_job_id":null,"html_url":"https://github.com/Raureif/WikipediaKit","commit_stats":{"total_commits":77,"total_committers":3,"mean_commits":"25.666666666666668","dds":0.06493506493506496,"last_synced_commit":"8a68910bae7253bf1aaefe4eb1251ccd2e494976"},"previous_names":[],"tags_count":19,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Raureif%2FWikipediaKit","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Raureif%2FWikipediaKit/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Raureif%2FWikipediaKit/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Raureif%2FWikipediaKit/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Raureif","download_url":"https://codeload.github.com/Raureif/WikipediaKit/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":226095601,"owners_count":17572957,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ios","macos","swift","swift3","tvos","watchos","wikipedia","wikipedia-api"],"created_at":"2024-08-05T23:00:36.234Z","updated_at":"2024-11-23T20:30:43.463Z","avatar_url":"https://github.com/Raureif.png","language":"Swift","readme":"**⚠️ On 6 July 2023, Wikimedia [introduced a breaking change](https://lists.wikimedia.org/hyperkitty/list/wikitech-l@lists.wikimedia.org/thread/4MVQQTONJT7FJAXNVOFV3WWVVMCHRINE/) to their Wikipedia API / [Mobile Content Service](https://phabricator.wikimedia.org/T328036), which broke the [`requestArticle`](#articles) feature in this framework.**\n\n## WikipediaKit · API Client Framework for Swift\n\nThe [Wikipedia API](https://www.mediawiki.org/wiki/Special:ApiSandbox) can do a lot, but it’s not easy to get started.\n\nWith WikipediaKit, it’s easy to build apps that search and show Wikipedia content—without worrying about the raw API. Instead of exposing all options and endpoints, WikipediaKit provides comfortable access to the most interesting parts for building a reader app. WikipediaKit comes with opinions and an attitude—but that’s the point!\n\nThe WikipediaKit framework is written in Swift, has no third-party dependencies, and runs on macOS, iOS, watchOS, and tvOS.\n\n## Installation\n\n### Swift Package Manager (preferred)\nWikipediaKit can be added to your Xcode project using the [Swift Package Manager](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app).\n\n### Carthage\nYou can use [Carthage](https://github.com/Carthage/Carthage) to install and update WikipediaKit.\n\n### Manual\nDrag and drop the `WikipediaKit.xcodeproj` to your app project and add the `WikipediaKit` embedded framework in your app project’s build settings.\n\n\n## Usage\n\n### Getting started\n\nThe `Wikipedia` class connects your app to Wikipedia’s API. You can search, get articles, and list nearby places by querying a freshly created `Wikipedia` instance…\n\n```swift\nlet wikipedia = Wikipedia()\n```\n\n…or by using the `shared` singleton instance:\n\n```swift\nlet wikipedia = Wikipedia.shared\n```\n\nBefore doing anything else, make sure to add your email address:\n\n```swift\nWikipediaNetworking.appAuthorEmailForAPI = \"appauthor@example.com\"\n```\n\nWikipediaKit will use this email address and your app’s bundle info to generate and send a `User-Agent` header. This will identify your app to Wikipedia’s servers with every API request, as required by the [API guidelines](https://www.mediawiki.org/wiki/API:Main_page#Identifying_your_client).\n\nThe `User-Agent` header is printed to your Xcode console when you make the first API request. It’ll look similar to this:\n\n```\nUser-Agent: ExampleApp/1.0 (com.example.ExampleApp; appauthor@example.com) WikipediaKit/1.0\n```\n\nPlease double-check that the `User-Agent` header is correct before shipping your app.\n\n### Return Type and Asynchronous Networking\n\nThe return type of all `Wikipedia` methods is\na standard [`URLSessionTask`](https://developer.apple.com/reference/foundation/urlsessiontask):\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\nlet searchSessionTask = Wikipedia.shared.requestOptimizedSearchResults(language: language, term: \"Soft rime\") { (searchResults, error) in\n    // This code will be called asynchronously\n    // whenever the results have been downloaded.\n    // …\n}\n```\n\nA `URLSessionTask` can be cancelled like this:\n\n```swift\nsearchSessionTask.cancel()\n```\n\nSee the [`URLSessionTask`](https://developer.apple.com/reference/foundation/urlsessiontask) documentation for further reading.\n\n### Languages\n\nA `WikipediaLanguage` has a language code, a localized name, an [autonym](https://en.wikipedia.org/wiki/Exonym_and_endonym), and sometimes a variant (e.g. `zh-hans` for Simplified Chinese and `zh-hant` for Traditional Chinese).\n\n```swift\n// French language, localized name for German, no variant\nlet l = WikipediaLanguage(code: \"fr\",\n                          localizedName: \"Französisch\", // FR in DE\n                          autonym: \"Français\") // FR in FR\n```\n\n\nWikipediaKit comes with a list of Wikipedia languages and their autonyms. This lets you initialize a `WikipediaLanguage` by passing the language code. Please note that if you use this shorthand method, the localized names will be in English.\n\n```swift\nlet language = WikipediaLanguage(\"fr\")\n// code: \"fr\", localizedName: \"French\", autonym: \"Français\"\n```\n\n### Search\n\nSearch Wikipedia—e.g. for the term “[Soft rime](https://en.wikipedia.org/wiki/Soft_rime)” in English—like this:\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\nlet _ = Wikipedia.shared.requestOptimizedSearchResults(language: language, term: \"Soft rime\") { (searchResults, error) in\n\n    guard error == nil else { return }\n    guard let searchResults = searchResults else { return }\n\n    for articlePreview in searchResults.items {\n        print(articlePreview.displayTitle)\n    }\n}\n```\n\nThe `searchResults` are a `WikipediaSearchResults` object.\n\n#### Search Batch Size (Paging Search Results)\n\nTo load more search results for a query, simply start another search for the same `language:` and `term:`, passing the previous `WikipediaSearchResults` object as the `existingSearchResults:` parameter.\n\nThe default batch size is `15`, but can be changed by passing a different number in the `maxCount` parameter.\n\n#### Search Methods\n\nThere are two supported search methods (`WikipediaSearchMethod`) to search for articles on Wikipedia. You can pass them to `requestSearchResults(method:language:term:)`.\n\n- `.prefix` searches the article titles only\n- `.fullText` searches the complete articles\n\n**For better search results quality,** use `requestOptimizedSearchResults(language:term:)`, which doesn’t take a `method:` parameter (see the example above). This will use the `.prefix` search and then fall back to the `.fullText` search whenever there are few or no results for a search term.\n\nYou can adjust the minimum number of results—before the fallback `.fullText` search is triggered—with the `minCount:` parameter.\n\n#### Search Thumbnail Image Size\n\nThe desired maximum pixel width of the `WikipediaArticlePreview`’s image URL can be adjusted in the optional `imageWidth:` parameter.\n\n#### Search Cache\n\nSearches are cached automatically until the app quits (see section on caching below).\n\n### Article Previews\n\n`WikipediaArticlePreview` objects represent search result items. They’re similar to full articles, but contain only an excerpt of the article text.\n\nThe `displayTitle` and `displayText` can be formatted via your `WikipediaFormattingDelegate`.\n\n### Articles\n\n*Update: Since WikipediaKit 3.0, this method uses the new Wikipedia REST API. The rewrite was a good opportunity to modernize WikipediaKit and return a `Result\u003cWikipediaArticle, WikipediaError\u003e` type.*\n\nLoad the article about “[Soft rime](https://en.wikipedia.org/wiki/Soft_rime)” in English like this:\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\nlet _ = Wikipedia.shared.requestArticle(language: language, title: \"Soft rime\") { result in\n    switch result {\n    case .success(let article):\n      print(article.displayTitle)\n      print(article.displayText)\n    case .failure(let error):\n      print(error)\n    }\n}\n```\n\n\nThe `displayTitle` and `displayText` can be formatted via your `WikipediaFormattingDelegate`.\n\nWikipedia articles come with a table of contents, stored in a array of `WikipediaTOCItem`. The section titles can be formatted in your `WikipediaFormattingDelegate`.\n\nTo query other available languages for a given article, use the `requestAvailableLanguages(for:)` call on your `Wikipedia` instance, passing the existing article.\n\nArticles are cached automatically until the app is restarted (see section on caching below).\n\n### Nearby Search\n\nThis search mode returns geo-tagged articles around a specific location. Pass in a coordinate (latitude and longitude) around which to search:\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\nlet _ = Wikipedia.shared.requestNearbyResults(language: language, latitude: 52.4555592, longitude: 13.3175333) { (articlePreviews, resultsLanguage, error) in\n\n    guard error == nil else { return }\n    guard let articlePreviews = articlePreviews else { return }\n\n    for a in articlePreviews {\n        print(a.displayTitle)\n        if let coordinate = a.coordinate {\n            print(coordinate.latitude)\n            print(coordinate.longitude)\n        }\n    }\n}\n```\n\n\n### Featured Articles\n\nThe `requestFeaturedArticles(language:date:)` query gets a list of the most popular articles for a specific date from Wikipedia’s official analytics.\n\n*Please note: Versions of WikipediaKit before 3.0 used the raw data from an older Wikipedia API to implement this feature. The new (current) implementation uses the same new API as the official Wikipedia app, which seems to filter the articles, stripping out potentially offensive content.*\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\nlet dayBeforeYesterday = Date(timeIntervalSinceNow: -60 * 60 * 48)\n\nlet _ = Wikipedia.shared.requestFeaturedArticles(language: language, date: dayBeforeYesterday) { result in\n    switch result {\n    case .success(let featuredCollection):\n\t    for a in featuredCollection.mostReadArticles {\n\t        print(a.displayTitle)\n\t    }\n    case .failure(let error):\n      print(error)\n    }\n}\n```\n\n### Image Metadata\n\nTo find out the URL for a given Wikipedia image at a specific size, use this call:\n\n```swift\nlet language = WikipediaLanguage(\"en\")\n\n// You can pass multiple images here.\n// Make sure to limit the number somehow\n// because the API server will bail out\n// if the query URL gets too long.\n\nlet urls = [\"https://en.wikipedia.org/wiki/File:Raureif2.JPG\"]\n\nlet _ = Wikipedia.shared.(language: language, urls: urls, width: 1000) { (imagesMetadata, error) in\n    guard error == nil else { return }\n    for metadata in imagesMetadata {\n\t    print(metadata.url) // URL for 1000px width version\n\t    print(metadata.description)\n\t    print(metadata.license)\n\t  }\n}\n\n```\n\nInstead of the `urls:` parameter, you can specify image IDs; in this case the `ids:` parameter would be `[\"File:Raureif2.JPG\"]`.\n\n## Delegates\n\nWikipediaKit comes with a few delegate protocols that help you track state, filter, and format.\n\n### Networking Delegate\n\n```swift\nWikipediaNetworking.sharedActivityIndicatorDelegate = MyActivityIndicatorDelegate.shared\n```\n\nSet a `WikipediaNetworkingActivityDelegate` to receive `start()` and `stop()` calls whenever a network operation starts and stops.\n\n### Formatting Delegate\n\n```swift\nWikipedia.sharedFormattingDelegate = MyFormattingDelegate.shared\n```\n\nThe `WikipediaArticle` and `WikipediaArticlePreview` classes have a `displayTitle` and a `displayText` property.\n\nYou can parse and reformat article texts, titles, and the table of contents in your `WikipediaFormattingDelegate` before it’s being cached.\n\n```swift\nclass MyFormattingDelegate: WikipediaTextFormattingDelegate {\n\n    static let shared = MyFormattingDelegate()\n\n    func format(context: WikipediaTextFormattingDelegateContext, rawText: String, title: String?, language: WikipediaLanguage, isHTML: Bool) -\u003e String {\n        // Do something to rawText before returning…\n        return rawText\n    }\n}\n```\n\n\n## Caching\n\nCaching happens automatically (*after* processing and formatting) for search results and articles. WikipediaKit uses simple `NSCache` instances.\n\nThere’s also the automatic [`NSURLCache`](http://nshipster.com/nsurlcache/), controlled by the server’s cache headers. You can modify the cache duration headers to be included API response in `Wikipedia.maxAgeInSeconds`.\n\n\n## Random Articles\n\nRequest an array of random `WikipediaArticlePreview` objects like this:\n\n```swift\nWikipedia.shared.requestRandomArticles(language: self.language, maxCount: 8, imageWidth: 640) {\n    (articlePreviews, language, error) in\n\n    guard let articlePreviews = articlePreviews else { return }\n\n    for article in articlePreviews {\n        print(article.displayTitle)\n    }\n}\n```\n\nWikipediaKit has this convenience function that gets one single random `WikipediaArticlePreview` at a time:\n\n```swift\nWikipedia.shared.requestSingleRandomArticle(language: self.language, maxCount: 8, imageWidth: 640) {\n    (article, language, error) in\n\n    guard let article = article else { return }\n\n    print(article.displayTitle)\n}\n```\n\nIf `maxCount` is larger than `1`, the surplus results from the API query are buffered in a shared `WikipediaRandomArticlesBuffer` object and will be returned one-by-one with every subsequent call of `requestSingleRandomArticle`. A new network request is only triggered when there are no buffered random articles left or when the query language changes.\n\n\n## About\n\nWikipediaKit was created by Frank Rausch.\n\n© 2017–22 Raureif GmbH / Frank Rausch\n\n### License\n\nMIT License; please read the `LICENSE` file in this repository.\n\n### Disclaimer\n\nThis project is not affiliated with the official Wikipedia projects or the Wikimedia Foundation.\n\n### Trademarks\n\nWikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.\n","funding_links":[],"categories":["Swift"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRaureif%2FWikipediaKit","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FRaureif%2FWikipediaKit","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FRaureif%2FWikipediaKit/lists"}