All Projects → Raureif → Wikipediakit

Raureif / Wikipediakit

Licence: mit
Wikipedia API Client Framework for Swift on macOS, iOS, watchOS, and tvOS

Programming Languages

swift
15916 projects
swift3
66 projects

Projects that are alternatives of or similar to Wikipediakit

SwiftVer
Easily Manage Versioning in MacOS, iOS, watchOS, and tvOS projects.
Stars: ✭ 23 (-91.48%)
Mutual labels:  tvos, watchos
Spine
Unofficial Spine runtime Swift library, allows you to play animations created in the Spine app (http://esotericsoftware.com).
Stars: ✭ 125 (-53.7%)
Mutual labels:  tvos, watchos
swift-standard-clients
Client declarations and live implementations for standard iOS managers
Stars: ✭ 28 (-89.63%)
Mutual labels:  tvos, watchos
CombineCoreBluetooth
A wrapper API for CoreBluetooth using Combine Publishers
Stars: ✭ 50 (-81.48%)
Mutual labels:  tvos, watchos
SMJJSONPath
JSONPath implementation in Objective-C
Stars: ✭ 28 (-89.63%)
Mutual labels:  tvos, watchos
Datez
📆 Breeze through Date, DateComponents, and TimeInterval with Swift!
Stars: ✭ 254 (-5.93%)
Mutual labels:  tvos, watchos
PotentCodables
🧪 PotentCodables - A potent set of implementations and extensions to the Swift Codable system
Stars: ✭ 32 (-88.15%)
Mutual labels:  tvos, watchos
Columbus
A feature-rich country picker for iOS, tvOS and watchOS.
Stars: ✭ 23 (-91.48%)
Mutual labels:  tvos, watchos
Wells
A lightweight diagnostics report submission system
Stars: ✭ 26 (-90.37%)
Mutual labels:  tvos, watchos
ios-watchos-tvos-macos-resources
Updated list of Swift frameworks and libraries for iOS, watchOS, tvOS and macOS.
Stars: ✭ 58 (-78.52%)
Mutual labels:  tvos, watchos
Jsonify
♨️A delightful JSON parsing framework.
Stars: ✭ 42 (-84.44%)
Mutual labels:  tvos, watchos
clevertap-ios-sdk
CleverTap iOS SDK
Stars: ✭ 39 (-85.56%)
Mutual labels:  tvos, watchos
Hostess.swift
A Swift implementation of NSHost that works on iOS, OS X and tvOS. Hostess.swift is safe to use in a framework because it does not require a bridging header. Hostess is Swift 4.0 (or newer) only and replaces the Swift 2.x only Host.swift.
Stars: ✭ 27 (-90%)
Mutual labels:  tvos, watchos
SwiftGenStrings
genstrings replacement for Swift that actually works
Stars: ✭ 29 (-89.26%)
Mutual labels:  tvos, watchos
OpenAPI-ObjectiveC
KKBOX Open API Developer SDK for iOS/macOS/watchOS/tvOS
Stars: ✭ 19 (-92.96%)
Mutual labels:  tvos, watchos
BlockiesSwift
Unique blocky identicons generator for Swift
Stars: ✭ 53 (-80.37%)
Mutual labels:  tvos, watchos
Apple-Platform-Security-Guides
Every Apple Platform Security Guide
Stars: ✭ 106 (-60.74%)
Mutual labels:  tvos, watchos
Mechanica
A cross-platform library of Swift utils to ease your iOS | macOS | watchOS | tvOS and Linux development.
Stars: ✭ 27 (-90%)
Mutual labels:  tvos, watchos
TermiNetwork
🌏 A zero-dependency networking solution for building modern and secure iOS, watchOS, macOS and tvOS applications.
Stars: ✭ 80 (-70.37%)
Mutual labels:  tvos, watchos
WebPKit
A framework that extends a variety of Cocoa APIs with capabilities for encoding and decoding WebP files for all of Apple's platforms.
Stars: ✭ 29 (-89.26%)
Mutual labels:  tvos, watchos

WikipediaKit · API Client Framework for Swift

The Wikipedia API can do a lot, but it’s not easy to get started.

With 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!

The WikipediaKit framework is written in Swift, has no third-party dependencies, and runs on macOS, iOS, watchOS, and tvOS.

If this doesn’t convince you to build a shiny new reader app for Wikipedia yourself, have a look at V for Wiki, the award-winning app that WikipediaKit was created for. The shipping version on the iOS App Store uses exactly the code that you can explore and download here.

Installation

Swift Package Manager (preferred)

WikipediaKit can be added to your Xcode project using the Swift Package Manager.

Carthage

You can use Carthage to install and update WikipediaKit.

Manual

Drag and drop the WikipediaKit.xcodeproj to your app project and add the WikipediaKit embedded framework in your app project’s build settings.

Usage

Getting started

The 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…

let wikipedia = Wikipedia()

…or by using the shared singleton instance:

let wikipedia = Wikipedia.shared

Before doing anything else, make sure to add your email address:

WikipediaNetworking.appAuthorEmailForAPI = "[email protected]"

WikipediaKit 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.

The User-Agent header is printed to your Xcode console when you make the first API request. It’ll look similar to this:

User-Agent: ExampleApp/1.0 (com.example.ExampleApp; [email protected]) WikipediaKit/1.0

Please double-check that the User-Agent header is correct before shipping your app.

Return Type and Asynchronous Networking

The return type of all Wikipedia methods is a standard URLSessionTask:

let language = WikipediaLanguage("en")

let searchSessionTask = Wikipedia.shared.requestOptimizedSearchResults(language: language, term: "Soft rime") { (searchResults, error) in
    // This code will be called asynchronously
    // whenever the results have been downloaded.
    // …
}

A URLSessionTask can be cancelled like this:

searchSessionTask.cancel()

See the URLSessionTask documentation for further reading.

Languages

A WikipediaLanguage has a language code, a localized name, an autonym, and sometimes a variant (e.g. zh-hans for Simplified Chinese and zh-hant for Traditional Chinese).

// French language, localized name for German, no variant
let l = WikipediaLanguage(code: "fr",
                          localizedName: "Französisch", // FR in DE
                          autonym: "Français") // FR in FR

WikipediaKit 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.

let language = WikipediaLanguage("fr")
// code: "fr", localizedName: "French", autonym: "Français"

Search

Search Wikipedia—e.g. for the term “Soft rime” in English—like this:

let language = WikipediaLanguage("en")

let _ = Wikipedia.shared.requestOptimizedSearchResults(language: language, term: "Soft rime") { (searchResults, error) in

    guard error == nil else { return }
    guard let searchResults = searchResults else { return }

    for articlePreview in searchResults.items {
        print(articlePreview.displayTitle)
    }
}

The searchResults are a WikipediaSearchResults object.

Search Batch Size (Paging Search Results)

To 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.

The default batch size is 15, but can be changed by passing a different number in the maxCount parameter.

Search Methods

There are two supported search methods (WikipediaSearchMethod) to search for articles on Wikipedia. You can pass them to requestSearchResults(method:language:term:).

  • .prefix searches the article titles only
  • .fullText searches the complete articles

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.

You can adjust the minimum number of results—before the fallback .fullText search is triggered—with the minCount: parameter.

Search Thumbnail Image Size

The desired maximum pixel width of the WikipediaArticlePreview’s image URL can be adjusted in the optional imageWidth: parameter.

Search Cache

Searches are cached automatically until the app quits (see section on caching below).

Article Previews

WikipediaArticlePreview objects represent search result items. They’re similar to full articles, but contain only an excerpt of the article text.

The displayTitle and displayText can be formatted via your WikipediaFormattingDelegate.

Articles

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<WikipediaArticle, WikipediaError> type.

Load the article about “Soft rime” in English like this:

let language = WikipediaLanguage("en")

let _ = Wikipedia.shared.requestArticle(language: language, title: "Soft rime") { result in
    switch result {
    case .success(let article):
      print(article.displayTitle)
      print(article.displayText)
    case .failure(let error):
      print(error)
    }
}

The displayTitle and displayText can be formatted via your WikipediaFormattingDelegate.

Wikipedia articles come with a table of contents, stored in a array of WikipediaTOCItem. The section titles can be formatted in your WikipediaFormattingDelegate.

To query other available languages for a given article, use the requestAvailableLanguages(for:) call on your Wikipediainstance, passing the existing article.

Articles are cached automatically until the app is restarted (see section on caching below).

Nearby Search

This search mode returns geo-tagged articles around a specific location. Pass in a coordinate (latitude and longitude) around which to search:

let language = WikipediaLanguage("en")

let _ = Wikipedia.shared.requestNearbyResults(language: language, latitude: 52.4555592, longitude: 13.3175333) { (articlePreviews, resultsLanguage, error) in

    guard error == nil else { return }
    guard let articlePreviews = articlePreviews else { return }

    for a in articlePreviews {
        print(a.displayTitle)
        if let coordinate = a.coordinate {
            print(coordinate.latitude)
            print(coordinate.longitude)
        }
    }
}

Featured Articles

The requestFeaturedArticles(language📅) query gets a list of the most popular articles for a specific date from Wikipedia’s official analytics.

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.

let language = WikipediaLanguage("en")

let dayBeforeYesterday = Date(timeIntervalSinceNow: -60 * 60 * 48)

let _ = Wikipedia.shared.requestFeaturedArticles(language: language, date: dayBeforeYesterday) { result in
    switch result {
    case .success(let featuredCollection):
	    for a in featuredCollection.mostReadArticles {
	        print(a.displayTitle)
	    }
    case .failure(let error):
      print(error)
    }
}

Image Metadata

To find out the URL for a given Wikipedia image at a specific size, use this call:

let language = WikipediaLanguage("en")

// You can pass multiple images here.
// Make sure to limit the number somehow
// because the API server will bail out
// if the query URL gets too long.

let urls = ["https://en.wikipedia.org/wiki/File:Raureif2.JPG"]

let _ = Wikipedia.shared.(language: language, urls: urls, width: 1000) { (imagesMetadata, error) in
    guard error == nil else { return }
    for metadata in imagesMetadata {
	    print(metadata.url) // URL for 1000px width version
	    print(metadata.description)
	    print(metadata.license)
	  }
}

Instead of the urls: parameter, you can specify image IDs; in this case the ids: parameter would be ["File:Raureif2.JPG"].

Delegates

WikipediaKit comes with a few delegate protocols that help you track state, filter, and format.

Networking Delegate

WikipediaNetworking.sharedActivityIndicatorDelegate = MyActivityIndicatorDelegate.shared

Set a WikipediaNetworkingActivityDelegate to receive start() and stop() calls whenever a network operation starts and stops.

Formatting Delegate

Wikipedia.sharedFormattingDelegate = MyFormattingDelegate.shared

The WikipediaArticle and WikipediaArticlePreview classes have a displayTitle and a displayText property.

You can parse and reformat article texts, titles, and the table of contents in your WikipediaFormattingDelegate before it’s being cached.

class MyFormattingDelegate: WikipediaTextFormattingDelegate {

    static let shared = MyFormattingDelegate()

    func format(context: WikipediaTextFormattingDelegateContext, rawText: String, title: String?, language: WikipediaLanguage, isHTML: Bool) -> String {
        // Do something to rawText before returning…
        return rawText
    }
}

Caching

Caching happens automatically (after processing and formatting) for search results and articles. WikipediaKit uses simple NSCache instances.

There’s also the automatic NSURLCache, controlled by the server’s cache headers. You can modify the cache duration headers to be included API response in Wikipedia.maxAgeInSeconds.

Random Articles

Request an array of random WikipediaArticlePreview objects like this:

Wikipedia.shared.requestRandomArticles(language: self.language, maxCount: 8, imageWidth: 640) {
    (articlePreviews, language, error) in

    guard let articlePreviews = articlePreviews else { return }

    for article in articlePreviews {
        print(article.displayTitle)
    }
}

WikipediaKit has this convenience function that gets one single random WikipediaArticlePreview at a time:

Wikipedia.shared.requestSingleRandomArticle(language: self.language, maxCount: 8, imageWidth: 640) {
    (article, language, error) in

    guard let article = article else { return }

    print(article.displayTitle)
}

If 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.

To Do

  • [ ] Improve unit tests
  • [ ] Pass request options in an array instead of function parameters

About

WikipediaKit was created by Frank Rausch (@frankrausch) for Raureif.

© 2017–20 Raureif GmbH / Frank Rausch

License

MIT License; please read the LICENSE file in this repository.

Disclaimer

This project is not affiliated with the official Wikipedia projects or the Wikimedia Foundation.

Trademarks

Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].