Swiftpack.co - Package - algolia/algoliasearch-client-swift

Build Status Carthage compatible SwiftPM Compatible CocoaPods CocoaPods Swift 4.0 Objective-C compatible

Algolia Search API Client for Swift and Objective-C

Algolia Search is a hosted full-text, numerical, and faceted search engine capable of delivering realtime results from the first keystroke. The Algolia Search API Client lets you easily use the Algolia Search REST API from your Swift code.

That being said, the library is 100% compatible with Objective-C

As a complement to this readme, you can browse the automatically generated reference documentation. (See also the offline-enabled version.)

API Documentation

You can find the full reference on the Algolia's website.

Table of Contents

  1. Supported platforms

  2. Install

  3. Quick Start

  4. Getting Help

Getting Started

Supported platforms

Our Swift client is supported on iOS, macOS, tvOS and watchOS, and is usable from both Swift and Objective-C.


Swift 5.0

  1. Add a dependency on InstantSearchClient:
    • CocoaPods: add pod 'InstantSearchClient', '~> 7.0' to your Podfile.
    • Carthage: add github "algolia/algoliasearch-client-swift" ~> 7.0.0 to your Cartfile.
    • SwiftPM: add .package(url:"https://github.com/algolia/algoliasearch-client-swift", from: "7.0.0") to your package dependencies array in Package.swift, then add InstantSearchClient to your target dependencies.
  2. Add import InstantSearchClient to your source files.

Swift 4.2

  1. Add a dependency on InstantSearchClient:
    • CocoaPods: add pod 'InstantSearchClient', '~> 6.0' to your Podfile.
    • Carthage: add github "algolia/algoliasearch-client-swift" ~> 6.0.0 to your Cartfile.
    • SwiftPM: add .package(url:"https://github.com/algolia/algoliasearch-client-swift", from: "6.0.0") to your package dependencies array in Package.swift, then add InstantSearchClient to your target dependencies.
  2. Add import InstantSearchClient to your source files.

Swift 4.1

  1. Add a dependency on InstantSearchClient:
    • CocoaPods: add pod 'InstantSearchClient', '~> 5.0' to your Podfile.
    • Carthage: add github "algolia/algoliasearch-client-swift" ~> 5.0.0 to your Cartfile.
    • SwiftPM: add .package(url:"https://github.com/algolia/algoliasearch-client-swift", from: "5.0.0") to your package dependencies array in Package.swift, then add InstantSearchClient to your target dependencies.
  2. Add import InstantSearchClient to your source files.

Quick Start

In 30 seconds, this quick start tutorial will show you how to index and search objects.

Initialize the client

You first need to initialize the client. For that you need your Application ID and API Key. You can find both of them on your Algolia account.

let client = Client(appID: "YourApplicationID", apiKey: "YourAPIKey")

Push data

Without any prior configuration, you can start indexing 500 contacts in the contacts index using the following code:

// Load content file
let jsonURL = Bundle.main.url(forResource: "contacts", withExtension: "json")
let jsonData = try! Data(contentsOf: jsonURL!)
let dict = try! JSONSerialization.jsonObject(with: jsonData!)

// Load all objects in the JSON file into an index named "contacts".
let index = client.index(withName: "contacts")


You can now search for contacts using firstname, lastname, company, etc. (even with typos):

// search by firstname
index.search(Query(query: "jimmie"), completionHandler: { (content, error) -> Void in
	if error == nil {
		print("Result: \(content)")
// search a firstname with typo
index.search(Query(query: "jimie"), completionHandler: { (content, error) -> Void in
	if error == nil {
		print("Result: \(content)")
// search for a company
index.search(Query(query: "california paint"), completionHandler: { (content, error) -> Void in
	if error == nil {
		print("Result: \(content)")
// search for a firstname & company
index.search(Query(query: "jimmie paint"), completionHandler: { (content, error) -> Void in
	if error == nil {
		print("Result: \(content)")


Settings can be customized to tune the search behavior. For example, you can add a custom sort by number of followers to the already great built-in relevance:

let customRanking = ["desc(followers)"]
let settings = ["customRanking": customRanking]
index.setSettings(settings, completionHandler: { (content, error) -> Void in
	if error != nil {
		print("Error when applying settings: \(error!)")

You can also configure the list of attributes you want to index by order of importance (first = most important):

Note: Since the engine is designed to suggest results as you type, you'll generally search by prefix. In this case the order of attributes is very important to decide which hit is the best:

let customRanking = ["lastname", "firstname", "company", "email", "city", "address"]
let settings = ["searchableAttributes": customRanking]
index.setSettings(settings, completionHandler: { (content, error) -> Void in
	if error != nil {
		print("Error when applying settings: \(error!)")


Previous Objective-C API Client

In July 2015, we released a new version of our Swift client, able to work with Swift and Objective-C. As of version 3 (April 2016), Swift has become the reference implementation for both Swift and Objective-C projects. The Objective-C API Client is no longer under active development. It is still supported for bug fixes, but will not receive new features. If you were using our Objective-C client, read the migration guide from Objective-C.

Migration guides

If you were using version 2.x of our Swift client, read the migration guide to version 3.x.

Swift 3

You can use this library with Swift by one of the following ways:

  • pod 'AlgoliaSearch-Client-Swift', '~> 4.8.1'
  • pod 'AlgoliaSearch-Client-Swift', :git => 'https://github.com/algolia/algoliasearch-client-swift.git', :branch => 'swift-3'

Getting Help


Stars: 149


Used By

Total: 0


Release 7.0.2 - 2019-12-13 16:11:15

  • Change SPM package name to make it consistent with Cocoapods and Carthage
  • Add compile-time version number generation for user agent

Swift 5.0 Support - 2019-04-19 11:51:40

The 7.0.0 version adds support for Swift 5.0 and Xcode 10.2. No new features have been added compared to version 6

Swift 4.2 Support - 2018-09-21 08:53:56

5.1.7 - 2018-05-04 13:09:07

Bug Fix

Aggregate "facet_stats" to the response when doing disjunctive faceting #522 Also fix a memory leak coming from NRURLSession #522

5.0.3 - 2017-10-03 08:03:45

New features

  • Index: Add deleteBy method and deprecate deleteByQuery method
  • PlacesClient: Add getObject(withID:completionHandler) method

5.0.1 - 2017-10-03 08:02:30

Support for Swift 4

- 2017-04-18 09:20:33

Miscellaneous changes

  • [offline] Better error reporting when building offline indices

- 2017-04-03 08:15:36

New features

  • Compatibility with Swift 3.1. (#294) Note: Swift 3.1 being source-compatible with Swift 3.0, version 4.7 was already compatible out of the box, but this one eliminates a few compile-time warnings.
  • Support new search parameters in the Query class:
    • disableExactOnAttributes (#369)
    • offset & length (#369)
    • percentileComputation (#365)
    • restrictHighlightAndSnippetArrays (#366)
  • Properties of the query classes (AbstractQuery and its derivates) are now KVO-observable (#339)
  • Add an option to choose a custom queue for completion handlers (#334). By default, the main queue is used.

Other changes

  • The userAgents property (managing the User-Agent HTTP header) is now a static property of the Client class. This should ease its use by other libraries, most notably InstantSearch Core.
  • [offline] Unify Index and OfflineIndex under a new Searchable protocol. This makes possible generic algorithms that work with any kind of index (MirroredIndex being a subclass of Index already).
  • Shorter README. The complete reference is now only on https://www.algolia.com/doc/api-client/swift/.

- 2017-02-08 12:35:30

New features

  • Support facetingAfterDistinct query parameter
  • Support maxFacetHits parameter when searching for facet values
  • [offline] Support offline search for facet values

Bug fixes

  • (#285) Fix race condition when searching while activating mirrored mode

Other changes

  • Update URL of generated reference documentation

- 2017-01-10 09:17:45

Bug fixes

  • [offline] Fix reachability handling in onlineOnly request strategy

- 2016-12-28 15:13:21

New features

  • [offline] Support manual building of local indices (MirroredIndex and OfflineIndex)
  • [offline] Support fallback logic when getting individual objects

Bug fixes

  • (#168) Use network reachability to decide whether to perform online requests
  • [offline] Fix race condition in instantiation of local index

- 2016-12-07 14:12:18

Note: This new version brings a major improvement in the request retry logic (fallback mechanism used when one or more API hosts are down or unreachable). For that reason, an upgrade to this or a later version is strongly recommended for all users of this API Client.

New features

  • (#158) Support the responseFields query parameter

Bug fixes

  • (#157) New retry logic: stateful host statuses. This should help largely minimize the impact of DNS resolution failures or other long-lasting network problems. Note that the timeout for statuses can be controlled via the AbstractClient.hostStatusTimeout property.

Other changes

  • Support more than one polygon in the insidePolygon query parameter. Warning: This breaks backward-compatibility for this specific parameter.

- 2016-11-18 18:27:44

New features

  • (#140) Support searching for facet values (Index.searchForFacetValues(...))
  • New method AbstractQuery.clear() to remove all parameters

Other changes

  • Open the Query class (along with some of its methods) to allow subclassing in other libraries
  • Make available as a static utility the method to build a query string from a dictionary of parameters (AbstractQuery.build(build(parameters:))

- 2016-11-09 23:43:28

New features

- 2016-11-02 09:45:19

New features

  • Add support for a list of languages in the ignorePlurals query parameter. Warning: This breaks backward-compatibility for this specific parameter.

Bug fixes

  • (#144) Fix compilation warning with Xcode 8.1

Other changes

  • (Objective-C bridging) Switch back to only one Query class. Note: This change is backward-compatible at the source level, provided that:
    • Objective-C code did not reference the BaseQuery type explicitly
    • Swift code did not reference the _objc_Query type explicitly

- 2016-10-03 11:55:59

New features

  • Support the createIfNotExists parameter in partial updates
  • [offline] Offline-only indices

Bug fixes

  • (#134) Use new format version when retrieving index settings
  • Fix asynchronous dispatch of some completion handlers (were called outside the main thread)

Other changes

  • Rename attributesToIndex to searchableAttributes

- 2016-09-15 17:15:41

  • Fix NSCopying support in Objective-C
  • [Offline mode] Upgrade to Offline Core 1.0

- 2016-09-14 08:32:15

This is a new major version, bringing incompatible changes, most of them due to Swift 3 support.

Note: You can find a detailed change log and migration instructions in the Migration guide to version 4.x.

Warning: This version requires Swift 3; it will not compile with Swift 2.x.

Warning: Cocoapods support for Swift 3 requires Cocoapods 1.1.0.rc.2 or later.

Swift 3 support

  • Adapt to the new Foundation API
  • Follow the Swift API Design Guidelines:
    • Argument labels:
      • Omit the first argument when the function name contains a complement (e.g. addObject) or when the purpose is obvious (search: with a query)
      • Label the first argument when the purpose is not obvious and not contained in the method name (e.g. batch(operations:))
      • Label all completion handlers explicitly. This is the convention adopted by the system's libraries (e.g. URLSession.dataTask(with:completionHandler:). Since the completion handler is likely to be a closure, the block can be moved out of the call site anyway, so the label is only required when passing a function/block reference.
    • Method names:
      • browse is now overloaded: browse(query:) and browse(from:).
    • Rename enum members to lower camel case
    • Rename constants to lower camel case (except notification names)
  • Better Objective-C mappings
    • Adjust method names when necessary for a better fit with this language
    • Objective-C specific types are no longer visible in Swift (well, technically, they still are, but you have to look harder...)
    • No underscore-suffixed properties any longer
  • Better typing
    • Use Error instead of NSError in completion handlers
      • Use dedicated error types
    • Use @discardableResult for methods returning Operation
    • Use Notification.Name for notifications
  • Prevent subclassing by not adopting the open access modifier

Other breaking changes

  • (Swift only) Better typing of complex properties through enums
  • Rename Index.indexName to Index.name.
  • Refactor index search cache handling into two properties to enable/disable (searchCacheEnabled) it and set the expiration delay (searchCacheExpiringTimeInterval), and one method to clear it (clearSearchCache())
  • Rename "slaves" to "replicas"

Other improvements

  • Improve cancellation of Index.waitTask()
  • Add tests for Objective-C bridging (online flavor only)
  • Make timeouts configurable
  • Index instances are now shared across a Client

- 2016-09-07 18:36:36

  • (#118) Add support for watchOS
  • (#120) Add an Index.getObjects() method with attributes to retrieve
  • Improve bandwidth usage of the "delete by query" helper
  • Fix memory leaks
  • Generate reference documentation for both the online and offline flavors

- 2016-08-09 09:23:50

  • Add explicit support for tvOS in the Cocoapods pod spec. (In fact, tvOS has been supported for a while in our code, but somehow never made it to the pod spec.) Note: not supported by the offline mode.
  • Add support for HTML documentation generation via Jazzy
  • Fix behavior of the exhaustiveFacetsCount response field when using disjunctive faceting
  • Migrate the User-Agent HTTP header to a new, more parseable format; now also includes the operating system's version.
  • Change value of ErrorDomain constant. Note: not a breaking change unless you relied on the value itself.
  • Update documentation

Offline mode

  • Expose last successful sync date (property MirroredIndex.lastSuccessfulSyncDate)

- 2016-07-29 08:59:47

  • New multipleQueries() method at index level
  • Fix cancellation of requests: in some edge cases, the completion handler could be called after cancellation
  • Fix potential crash when cancelling requests (unsafe assertions were made)

The following changes are for the offline mode only:

  • New offline fallback strategy. Warning: breaking change: preventive search no longer supported.
  • Offline requests now also work for disjunctive faceting
  • The searchMirror() method has been renamed to searchOffline(), for better consistency with the newly introduced searchOnline() method.
  • Improve detection of non-existent indices

- 2016-07-25 10:09:57

  • New Client.isAlive() method (/1/isalive endpoint)
  • Completion handler is now mandatory for multiple queries. Warning: breaking change
  • (#88) Fix passing of strategy parameter in multiple queries (should be POST instead of GET)
  • (#103) Fix URL encoding of path components (e.g. spaces in index names)
  • Add test case for TCP connection dropping

- 2016-06-29 08:11:22

  • (#77) Support a list of languages as a value for the removeStopWords query parameter. Warning: The type of the corresponding property had to be degraded from Bool? to AnyObject?; as a consequence, the getter suffers from an incompatible change (but not the setter).
  • (#79) Support aroundRadius=all in query parameters
  • (#76) Support the exactOnSingleWordQuery query parameter
  • (#76) Support the alternativesAsExact query parameter
  • (#74) Support Swift 2.3
  • (#75) Fix iTunes Connect submission issue when using Carthage: minimum iOS version is now 8.0
  • Update documentation

- 2016-05-27 09:59:44

  • Fix OS X support in Cocoapods

- 2016-05-26 16:12:07

  • Support iOS 7.0
    • Warning: Because Cocoapods uses dynamic frameworks and Swift is not supported in dynamic frameworks on iOS 7, iOS 7 support is not possible through Cocoapods.
    • Warning: Due to unavailability of simulators earlier than iOS 8.1 in Xcode 7.3, iOS 7 remains untested.
  • README updated
  • [Test] Add test case for DNS time-out

Experimental features

  • Offline mode. Note: requires the Algolia Search Offline Core library. Warning: beta version.

- 2016-05-09 08:43:07

  • Add tvOS target
  • Restore Carthage support
  • Add typed properties for query parameters filters and numericFilters
  • Shuffle host array at init time, for better load balancing
  • Update documentation
  • Fix unit tests: remove broken "keep alive" test case

- 2016-04-13 10:19:10

This major version brings new features and bug fixes. In addition, a lot of refactoring has been performed to achieve better Objective-C bridging, better maintainability, as well as to align the Swift client with the other Algolia API clients.

As a consequence, the public interface has changed in an incompatible way. Please refer to our Migration Guide for detailed instructions.

New features

  • Allow arbitrary query parameters to be specified: the Query class provides low-level, untyped accessors in addition to the higher-level, typed properties.
  • Allow arbitrary HTTP headers to be specified (Client.headers)
  • Asynchronous requests are cancellable: asynchronous methods return an NSOperation instance, making it possible to call cancel() on it.
  • Timeout settings now user-configurable
  • Batch operation support
  • Multiple queries strategy parameter support
  • Disjunctive faceting helper
  • Delete by query helper
  • Browse iterator helper (BrowseIterator)


  • Asynchronous methods completion block argument renamed to completionHandler for better consistency with the system libraries (in particular NSURLSession)
  • Align Query class parameters with the REST API
  • Remove operations requiring an admin API key. (The admin key should never be used on the client side.)
  • Browse methods now only low-level. (For high-level iteration, use the BrowseIterator helper; see above.)
  • Remove accessors to deprecated HTTP headers


  • Full Objective-C bridging: all features are now available from Objective-C.
  • More consistent error handling
  • Fix percent-escaping of query parameters in URLs
  • Fix Swift 2.2 deprecation warnings
  • HTTP headers can now be changed during the client's lifetime

Misc. improvements

  • Minimize public interface
  • Update documentation
  • Add test cases

- 2015-06-16 09:56:41

- 2015-06-09 07:48:50

- 2015-06-08 09:10:02