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

Algolia for Swift

The perfect starting point to integrate Algolia within your Swift project

DocumentationCommunity ForumStack OverflowReport a bugFAQSupport

✨ Features

  • Pure cross-platform Swift client
  • Typed requests and responses
  • Widespread use of Result type
  • Uses the power of Codable protocol for easy integration of your domain models
  • Thread-safe clients
  • Detailed logging
  • Injectable HTTP client

Install

Swift Package Manager

The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies. Since the release of Swift 5 and Xcode 11, SPM is compatible with the iOS, macOS and tvOS build systems for creating apps.

To use SwiftPM, you should use Xcode 11 to open your project. Click File -> Swift Packages -> Add Package Dependency, enter InstantSearch repo's URL.

If you're a framework author and use Swift API Client as a dependency, update your Package.swift file:

let package = Package(
    // 8.0.0 ..< 9.0.0
    dependencies: [
        .package(url: "https://github.com/algolia/algoliasearch-client-swift", from: "8.0.0")
    ],
    // ...
)

Add import AlgoliaSearchClient to your source files.

Cocoapods

CocoaPods is a dependency manager for Cocoa projects.

To install Algolia Swift Client, simply add the following line to your Podfile:

pod 'AlgoliaSearchClient', '~> 8.0'
# pod 'InstantSearchClient', '~> 6.0'` // Swift 4.2
# pod 'InstantSearchClient', '~> 5.0'` // Swift 4.1

Then, run the following command:

$ pod update

Carthage

Carthage is a simple, decentralized dependency manager for Cocoa.

  • To install InstantSearch, simply add the following line to your Cartfile:
github "algolia/algoliasearch-client-swift" ~> 8.0.0
# github "algolia/algoliasearch-client-swift" ~> 6.0.0` // Swift 4.2
# github "algolia/algoliasearch-client-swift" ~> 5.0.0` // Swift 4.1
  • Launch the following commands from the project directory (for v.8.0+)
carthage update
./Carthage/Checkouts/algoliasearch-client-swift/carthage-prebuild
carthage build

If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained over at Carthage.

💡 Getting Started

Initialize the client

To start, you need to initialize the client. To do this, you need your Application ID and API Key. You can find both on your Algolia account.

let client = Client(appID: "YourApplicationID", apiKey: "YourAdminAPIKey")
let index = client.index(withName: "your_index_name")

Push data

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

struct Contact: Encodable {
  let firstname: String
  let lastname: String
  let followers: Int
  let company: String
}

let contacts: [Contact] = [
  .init(firstname: "Jimmie", lastname: "Barninger", followers: 93, company: "California Paint"),
  .init(firstname: "Warren", lastname: "Speach", followers: 42, company: "Norwalk Crmc")
]

let index = client.index(withName: "contacts")
index.saveObjects(contacts, autoGeneratingObjectID: true) { result in
  if case .success(let response) = result {
    print("Response: \(response)")
  }
}

Search

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

index.search(query: "jimmie") { result in
  switch result {
  case .failure(let error):
    print("Error: \(error)")
  case .success(let response):
    print("Response: \(response)")
  }
}

Configure

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 settings = Settings()
  .set(\.customRanking, to: [.desc("followers")])
index.setSettings(settings) { result in
  if case .failure(let error) = result {
    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 settings = Settings()
  .set(\.searchableAttributes, to: ["lastname", "firstname", "company"])
index.setSettings(settings) { result in
  if case .failure(let error) = result {
    print("Error when applying settings: \(error)")
  }
}

For full documentation, visit the Algolia Swift API Client's documentation.

📝 Examples

You can find code samples in the Algolia's API Clients playground.

📄 License

Algolia Swift API Client is an open-sourced software licensed under the MIT license.

Notes

Objective-C support

The Swift API client is compatible with Objective-C up to version 7.0.5. Please use this version of the client if you're working with an Objective-C project.

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

  • Need help? Ask a question to the Algolia Community or on Stack Overflow.
  • Encountering an issue? Before reaching out to support, we recommend heading to our FAQ where you will find answers for the most common issues and gotchas with the client.
  • Found a bug? You can open a GitHub issue.

Github

link
Stars: 159

Dependencies

Used By

Total: 0

Releases

8.1.2 - 2020-10-06 12:00:02

  • Update min iOS version for compatibility with Xcode 12 and SwiftLog dependency version (#668) Thanks @rmenezes
  • Change browse with Cursor HTTP method from GET to POST for better reliability (#671)
  • Fix SearchResponse's automaticRadius is wrong type (#673)
  • Fix incorrect coding key for sortFacetsBy search parameter value (#674)

8.1.1 - 2020-09-17 20:32:24

  • Fix infinite hosts rotation within retry strategy (#664)
  • Add explicit percent encoding for plus sign in the browse cursor, lack of which causes browse API call error

8.1.0 - 2020-08-04 14:24:38

This minor release adds a possibility to update multiple fields of the record using partiaUpdate method with new dictionary syntax:

index.partialUpdateObject(withID: "userAccountID", with: [
  "name": "John Doe",
  "postsCount": 2000,
  "followers": .add(value: "nightStranger51", unique: false),
  "followersCount": .increment(value: 20),
  "likes": .incrementSet(value: 15)
])

- 2020-07-28 11:52:39

  • Add Xcode 12 compatibility
  • Add Client typealias for SearchClient to simplify the transition from v7

Swift API Client v8 - 2020-07-20 17:23:34

Meet brand new Swift API Client v8!

Universal

It’s a pure stand-alone Swift client so it is not tighten to any platform. In comparison with the previous version, it provides many new methods and from now can be used as a full-fledged client including server side applications.

Provides good Results

Each API call result is now represented by built-in Swift Result type which facilitates processing of the results returned by the API method and to dispatch them to other parts of your application.

Codable all the things

The interaction with API client is drastically simplified thanks to usage of built-in Encodable/Decodable protocols. Integration of Codable models existing in your project had never been easier.

Advanced Keypaths usage

Build API Client structures using the power of Swift keypaths

Rich code documentation

Each method is documented with detailed description of each parameter

Verbosity

The new client is verbose so it let know what’s going on while you are using the client. You won't miss if something went wrong. It’s up to you to define which level of logs you might want to see in your console. You can change it using AlgoliaSearchClient.Logger.minSeverityLevel value.

7.0.5 - 2020-06-16 13:56:27

  • Fix task!.resume() to task?.resume() call crash in extreme circumstances in the Request.swift class. This is to be on the safe side

7.0.4 - 2020-06-16 13:53:59

  • Fix Mac Catalyst bug by excluding CoreTelephony dependency code for Mac Catalyst apps

7.0.3 - 2020-06-16 13:50:05

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