Giter Club home page Giter Club logo

algoliasearch-client-swift's Introduction

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.20.1 ..< 9.0.0
    dependencies: [
        .package(url: "https://github.com/algolia/algoliasearch-client-swift", from: "8.20.1")
    ],
    // ...
)

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.20'
# 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.20
# 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)")
    do {
      let foundContacts: [Contact] = try response.extractsHits()
      print("Found contacts: \(foundContacts)")
    } catch let error {
      print("Contact parsing error: \(error)")
    }
  }
}

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.

Use the Dockerfile

If you want to contribute to this project without installing all its dependencies, you can use our Docker image. Please check our dedicated guide to learn more.

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

algoliasearch-client-swift's People

Contributors

aallam avatar alexfish avatar algolia-bot avatar algoliareadmebot avatar argon avatar cbaptiste avatar dethi avatar fjcaetano avatar fluf22 avatar georgeerickson avatar hawflakes avatar jonathanbouaziz avatar kaioelfke avatar loryhuz avatar mackoj avatar mannuch avatar mobilealgolia avatar mpclarkson avatar pixelastic avatar redox avatar renovate[bot] avatar rmenezes avatar robertmogos avatar sarahdayan avatar sisoje avatar speedblue avatar spinach avatar vladislavfitz avatar xiaowenvc avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

algoliasearch-client-swift's Issues

Swift 2.3 / 3.0

Hi!
What is the roadmap / plan for Swift 2.3 & 3 conversion?

Xcode 7.3: lot of warnings

Hi,
After installed Xcode 7.3 when I build with Carthage I have a lot of warnings:

warning: 'var' parameters are deprecated and will be removed in Swift 3
warning: '++' is deprecated: it will be removed in Swift 3
warning: keyword 'protocol' does not need to be escaped in argument list
warning: use of 'typealias' to declare associated types is deprecated; use 'associatedtype' instead

ld: warning: embedded dylibs/frameworks only run on iOS 8 or later

Hi,
Following Algolia Search with Carthage:

  • carthage version: 0.16.2
  • xcodebuild -version: Xcode 7.3.1 Build version 7D1014
  • Are you using --no-build? No
  • Are you using --no-use-binaries? No
  • Are you using --use-submodules? No

Cartfile

github "algolia/algoliasearch-client-swift" == 3.2.1

Cartage Output

$ carthage update --platform iOS
*** Cloning algoliasearch-client-swift
*** Checking out algoliasearch-client-swift at "3.2.1"
ld: warning: embedded dylibs/frameworks only run on iOS 8 or later
ld: warning: embedded dylibs/frameworks only run on iOS 8 or later
ld: warning: embedded dylibs/frameworks only run on iOS 8 or later
ld: warning: embedded dylibs/frameworks only run on iOS 8 or later

I don't have those warnings with Algolia Search version 2.3. Something must be wrong configured in your project.

Cancel a search request

Hi there,

Is there a way to cancel requests?
I could only find the following internal method in the Client:

/// Cancel a queries. Only the last ten queries can be cancelled.
    func cancelQueries(method: HTTPMethod, path: String) {
        for request in requestBuffer {
            if request.request.URL!.path! == path {
                if request.request.HTTPMethod == method.rawValue {
                    request.cancel()
                }
            }
        }
    }

Is there or are there plans to implement public methods for cancelling requests?

Thank you for your help.

Gives compilation error while migrating from swift 1.2 to 2.0

I am using pod 'AlgoliaSearch-Client-Swift', '~> 1.4', all working well with swift 1.2. But as soon as I shifted to Xcode 7, it raised error in "Network.swift" and "Index.swift". Is anyone facing the same problem? or could anyone guide me to resolve this issue?

Searching on index with spaces on its name crashes app

There is an exception thrown when searching on an index with spaces on its name (e.g. "Index with space").

The solution is correctly implementing Helpers class's urlEncode() function:

Current implementation:

func urlEncode() -> String {
        let customAllowedSet = NSCharacterSet(charactersInString: "!*'();:@&=+$,/?%#[]").invertedSet
        return stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet)!
    }

Proposed solution:

func urlEncode() -> String {
        return stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
    }

Unit tests in Objective-C

Since the Swift client is meant to be called from Objective-C, unit tests in Objective-C seem necessary to confirm that the bridging works properly.

Support iOS 7

The only non-iOS 7 compliant part of the code seems to be setting the underlyingQueue on the Client's operation queue... which appears to be unused.

WARNING: Simulators below iOS 8.1 are not provided by Xcode 7.3, so the iOS 7 code will remain untested.

Refs #62.

Run completion handlers in a background thread

Currently, completion handlers are run on the main thread. This eases the implementation in simple cases, but when the completion handler performs costly computation, it actually makes things more complicated. In those cases, it would be easier if the completion handler ran on a background queue, and it were up to the client code to dispatch to the main thread. (By the way, this is what system-provided asynchronous methods do; e.g. NSURLSession.dataTaskWithURL(_:completionHandler:).)

Unfortunately, we cannot change the default behavior without breaking client code. But what about providing an option (at the client level) to run completion handlers in the background?

Refactor the way to cancel network request

  • We should be able to cancel any request, not just searches.
  • We should return an object that can be acted upon, rather than providing a separate cancelQueries() method.
  • Caution: think about the synchronous methods.
  • Caution: think about the offline mode.

Migrate `User-Agent` header to new conventions

The new conventions being an array of components separated by semicolons:

Algolia for $LANGUAGE ($VERSION1); Library X ($VERSION2); Library Y ($VERSION2)

We should make it easily configurable, so that the future helpers can easily add their version to the list without destroying anything.

index.getObject Content Result Cast issue

Hi!
I am using the public func getObject(objectID: String, block: CompletionHandler)
my "content" result is a JSON result, however, I am getting a compiler warning with Swift 2.1

let foundObject = content as! NSDictionary
"Cast from '[String: AnyObject]?' to unrelated type 'NSDictionary' always fails"

Any ideas?

tvOS not supported in pod file

I've added the pod to my pod file and when I try to do a pod install I get the following error message in terminal.

[!] The platform of the target AppName-tvOS (tvOS 9.0) is not compatible with AlgoliaSearch-Client-Swift (3.3), which does not support tvos.

Clarify Objective-C bridging

It would be nice to have optionals for every parameter... but value types optionals are not bridgeable to Objective-C. We should therefore maybe use NSNumber, but it's not as nice for Swift clients. Should we provide two flavours of each value type property?

Provide a synchronous flavour of query methods

That's something we do in other clients. It can be useful when the user already has a background thread which she uses to perform operations. In this case, synchronous calls lead to more straightforward code while not degrading end-user performance.

Offline Cache

It would be great to be able to customize the cache to use things like NSURLRequestReturnCacheDataElseLoad which allows me to at least show something to the user when their device is offline, regardless of age or expiration. For example, my app shows a list of movie reviews. If the user starts reading a review but leaves and comes back later to finish reading (this time their device is offline), I would love to still be able to show them the same content they were viewing last time they were online. Is this something you would consider adding as an option?

Issue with Carthage

Hi,

Config

  • Xcode 7.2.1 (7C1002)
  • Carthage 0.15

Cartfile

github "algolia/algoliasearch-client-swift" == 2.1.0

Carthage command

carthage update --platform iOS

The issue

When I build and run my project on the device everything is ok
If I try to build my project on the simulator it's generate some errors:

ld: warning: ignoring file .../Build/Products/Debug-iphonesimulator/AlgoliaSearch.framework/AlgoliaSearch, file was built for i386 which is not the architecture being linked (x86_64): .../Build/Products/Debug-iphonesimulator/AlgoliaSearch.framework/AlgoliaSearch
...
Undefined symbols for architecture x86_64:
"AlgoliaSearch.Client.(init (AlgoliaSearch.Client.Type) -> (appID : Swift.String, apiKey : Swift.String, queryParameters : Swift.String?, tagFilters : Swift.String?, userToken : Swift.String?, hostnames : [Swift.String]?) -> AlgoliaSearch.Client).(default argument 4)", referenced from:
      TestAlgolia.Test.init (TestAlgolia.Test.Type)() -> TestAlgolia.Test in Test.o
...
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

X-Algolia-QueryParameters is missing

We can set the X-Algolia-TagFilters and the X-Algolia-UserToken header, but the new X-Algolia-QueryParameters is missing.

We could probably create something like:

let client = AlgoliaSearch.Client(appID: "xxxxxxx", apiKey: "xxxxxxxxxxxxx", queryParameters:"tagFilters=xxxxxxxx")

Rename `fullTextQuery` to `query`

I think we should rename fullTextQuery to query to fit the other API clients & the REST API.
Is it possible to deprecate it and to be backward compliant?

tvOS Target

Would you mind adding a tvOS target? I was able to and it seem to work fine.

Batch requests (generic method)

Batch requests are used behind the scenes in a few methods, but there is currently no generic way to issue a batch request. -> Implement it.

watchOS

Hi!
Is there any reason why your library couldn't work on watchOS?

Strategy parameter not working

Hi,

I contacted support today about strategy parameter in multiple query, I didn't understand its behavior because it's actually not working as expected and documentation was wrong apparently.

It's should be passed as POST parameter. Here is the temp fix I did on my side:
#87

You can reproduce by setting the strategy to "stopIfEnoughMatches", if you reach the number of hits of the first query for example, you'll also get hits for other queries, so the parameter is not taken.

Thanks !

iTunes connect submission issue

Invalid Info.plist value. The value for the key 'MinimumOSVersion' in bundle MyApp.app/Frameworks/AlgoliaSearch.framework is invalid. The minimum value is 8.0

It's currently not possible to submit an app that uses algoliasearch-client-swift via Carthage, because when the the framework is built via Carthage minimumosversion is set to 7.0, however it must be 8.0 or higher.

Remove admin API key-only operations

It does not make sense to have client methods for requests requiring an admin API key, as this key should remain on the back-end.

So we should remove:

  • Global API keys management
  • Per-index API keys management
  • Logs retrieval

numericFilters?

I am having difficulty finding numericFilters in the 3.0 SDK..
I used to be able to do a query with a numericFilter to find an record with a specific number.

Shuffle the default host arrays at client init time

The goal is to systematically avoid overloading the first non-DSN host upon failure. Shuffling should be done once and for all, as retrying a different host every time would likely imply opening a new connection, therefore incur a big overhead. Randomization across all users should be enough to guarantee proper load balancing.

Can't import in Vc - Cannot import module being compiled

I have tried installing via Cocapods and get the following error when trying to import Algolia.
Any ideas how to get it working?

Have tried cleaning the project.

Here is the Pod file:

# Uncomment this line to define a global platform for your project
# platform :ios, '8.0'
# Uncomment this line if you're using Swift
use_frameworks!

target 'Algolia' do
pod 'AlgoliaSearch-Client-Swift', '~> 1.4'
end

Improve type safety of `Client.multipleQueries`'s arguments

Currently, we are passing the queries as a completely untyped array, but we still require each item to be a dictionary with two keys: index name and query object. A more strongly typed argument would be welcome, for example like the IndexQuery class used on Android.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.