All tutorials

Swift

intermediate

This what3words Swift wrapper gives you programmatic access to the what3Words public API v3.

The what3words API is a fast, simple interface which allows you to convert 3 word addresses such as ///filled.count.soap to latitude and longitude coordinates such as (-0.203586, 51.521251) and vice versa. It features a powerful AutoSuggest function, which can validate and autocorrect user input and limit it to certain geographic areas (this powers the search box on our map site). It allows you to request a section of the what3words grid (which can be requested as GeoJSON for easy display on online maps), and to request the list of all languages supported by what3words. For advanced users, AutoSuggest can be used to post-process voice output. See links on the left to navigate.

All coordinates are latitude,longitude pairs in standard WGS-84 (as commonly used worldwide in GPS systems). All latitudes must be in the range of -90 to 90 (inclusive).

You will need a what3words API key to complete this tutorial.

2

Installation

Swift Package Manager

You can install this with Swift Package Manager by adding the URL below under Swift Packages under your project settings:

https://github.com/what3words/w3w-swift-wrapper.git
Copied

CocoaPods (iOS 9+, OS X 10.10+)

You can use CocoaPods to install w3w-swift-wrapper by adding it to the target in your Podfile:

pod 'W3WSwiftApi', :git => 'https://github.com/what3words/w3w-swift-wrapper.git'
Copied

Note:

Don’t forget, if you are running on device you need to set the App Transport Security Settings in your Info.plist as you would any app communicating with a server

Also, if you are using the Voice API on device, you should include Microphone permissions

3

Usage

Import

In any swift file you use the what3words API, import the following:

import W3WSwiftApi
import CoreLocation
Copied

Initialise

Use the following code with your API key to initialize the API:

let api = What3WordsV3(apiKey: "YourApiKey")
Copied

In the case that you run our Enterprise Suite API Server yourself, you may specifty the URL to your own server like so:

let api = What3WordsV3(apiKey: "YourApiKey", apiUrl: "https://api.yourserver.com")
Copied

Additionally, if you run the Enterprise Suite API Server there is another optional setup() parameter: customHeaders. Use this if you need to send custom headers to your own server:

let api = What3WordsV3(apiKey: "YourApiKey", apiUrl: "https://api.yourserver.com", customHeaders: ["x-header-1":"value-1", "x-header-2":"value-2"])
Copied
4

Functions

Each call takes a completion block as the last parameter. This allows Swift’s trailing closure syntax to be used. The closure’s parameters contain the results. If there was a problem with any call, it will be indicated by the error object.

Convert To 3 Word Address

Convert coordinates, expressed as latitude and longitude to a 3 word address.

This function takes the latitude and longitude as a CLLocationCoordinate2D object

The values returned from the convertTo3wa method are described in the API documentation.

let coords = CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)
api.convertTo3wa(coordinates: coords, language: "en") { square, error in
    print(square?.words ?? "")
}
Copied

Convert To Coordinates

Convert a 3 word address to a position, expressed as coordinates of latitude and longitude.

This function takes the words parameter as a string of 3 words 'table.book.chair'

The values returned from the convertToCoordinates method are described in the API documentation.

api.convertToCoordinates(words: "filled.count.soap") { square, error in
  print(square?.coordinates ?? "")
}
Copied

AutoSuggest

Returns a list of 3 word addresses based on user input and other parameters.

This method provides corrections for the following types of input error:

  • typing errors
  • spelling errors
  • misremembered words (e.g. singular vs. plural)
  • words in the wrong order

The autosuggest method determines possible corrections to the supplied 3 word address string based on the probability of the input errors listed above and returns a ranked list of suggestions. This method can also take into consideration the geographic proximity of possible corrections to a given location to further improve the suggestions returned.

  • voice
    If you have a VoiceAPI enabled account, you may also call autosuggest with audio data for voice recognition. In order for this to work, you must add a Voice API plan to your account. There is a minimal example of this below, but detailed information can be found here

Input 3 word address
You will only receive results back if the partial 3 word address string you submit contains the first two words and at least the first character of the third word; otherwise an error message will be returned.

We have prepared a regex, and example code to help you filter results before calling autosuggest. Please see our regex documentation

Clipping and Focus

We provide various clip policies to allow you to specify a geographic area that is used to exclude results that are not likely to be relevant to your users. We recommend that you use the clipping to give a more targeted, shorter set of results to your user. If you know your user’s current location, we also strongly recommend that you use the focus to return results which are likely to be more relevant.

In summary, the clip policy is used to optionally restrict the list of candidate autosuggest results, after which, if focus has been supplied, this will be used to rank the results in order of relevancy to the focus.

The values returned from the autosuggest method are described in the what3words REST API documentation.

Usage

The first parameter is the partial three words, or voice data. The second optional parameter is the options for the autosuggest function. The last parameter is the completion block.

api.autosuggest(text: "filled.count.soa") { (suggestions, error) in
  for suggestion in suggestions ?? [] {
    print("\(suggestion.words ?? "") is near \(suggestion.nearestPlace ?? "")")
  }
}
Copied

Focus on one particular place

let coords = CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)
api.autosuggest(text: "flottons.annulons.garço", options: W3WOption.focus(coords)) { (suggestions, error) in
  print(suggestions ?? "")
}
Copied

Focus on (51.4243877,-0.34745) and ask for suggestions from a French three word fragment:

let coords = CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)
let options = W3WOptions().focus(coords).clipToCountry("GB")
api.autosuggest(text: "flottons.annulons.garço", options: options) { (suggestions, error) in
  print(suggestions ?? "")
}
Copied

Voice API Example

The what3words Voice API allows a user to say three words into any application or service, with it returning a configurable list of what3words address suggestions, all through a single API call.

In order for this to work, you must add a Voice API plan to your account.

This example instantiates a W3WMicrophone which provides an audio stream to autosuggest(audio:) which begins recording when autosuggest is called. For information on W3WMicrophone and customizing your own W3WAudioStream for autosuggest(audio:) see the Voice API README.

// make a microphone
let microphone = W3WMicrophone()

// call autosuggest
api.autosuggest(audio: microphone, language: "en") { suggestions, error in
  for suggestion in suggestions ?? [] {
    print(suggestion.words ?? "no suggestions")
  }
}
Copied

Also, W3WMicrophone has a callback closure W3WMicrophone.volumeUpdate: (Double) -> () that provides amplitude information useful for animating user feedback. See the the Voice API example, and more information is avialable in the VoiceAPI README.

Available Languages

This function returns the currently supported languages for text based autosuggest(text:) calls. It will return the two letter code (ISO 639), and the name of the language both in that language and in English.

The values returned from the convertTo3wa method are described in the what3words REST API documentation

api.availableLanguages() { (languages, error) in
  for language in languages ?? [] {
    print(language.code, language.name, language.nativeName)
  }
}
Copied

For the available Voice API langauges call api.availableVoiceLanguages(completion:) which works exactly the same way.

Grid Section

Returns a section of the 3m x 3m what3words grid for a given area. The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig error will be returned. Latitudes must be >= -90 and <= 90, but longitudes are allowed to wrap around 180. To specify a bounding-box that crosses the anti-meridian, use longitude greater than 180. Example value: 50.0, 179.995, 50.01, 180.0005.

The values returned from the gridSection function are described in the what3words REST API documentation

let southWest = CLLocationCoordinate2D(latitude: 52.208867, longitude: 0.117540)
let northEast = CLLocationCoordinate2D(latitude: 52.207988, longitude: 0.116126)

api.gridSection(southWest: southWest, northEast: northEast) { (lines, error) in
  print("Line count: ", lines?.count ?? "zero")
}
Copied

Handling Errors

All functions call the completion block with error as the second parameter. All Swift what3words error types are of enum type and conform to CustomStringConvertible, so they can be used with String(describing: error):

api.convertTo3wa(coordinates: CLLocationCoordinate2D(latitude: 51.4243877, longitude: -0.34745)) { square, error in
  if let e = error {
    print(String(describing: e))
  } else {
    print(square?.words ?? "")
  }
}
Copied
Api call errors are of type W3WError enum and the voice autosuggest call returns a W3WVoiceError enum.

Related tutorials

Back to top