W3WError
enum and the voice autosuggest
call returns a W3WVoiceError
enum.As a reminder, emergency services can make use of the what3words API for free, and we have a dedicated plan for NGOs and registered charities. If your organisation falls within these categories, please get in touch. For any questions or assistance, feel free to reach out to support@what3words.com.
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).
Full sample apps for the wrapper can be found in our Github repo
iOS Sample Apps
You can install this with Swift Package Manager by adding the URL below under Swift Packages under your project settings:
Swift Package Manager
You can use CocoaPods to install w3w-swift-wrapper by adding it to the target in your Podfile:
pod 'what3words', :git => 'https://github.com/what3words/w3w-swift-wrapper.git'
Don’t forget, if you are running on a 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
In any swift file you use the what3words API, import the following:
import W3WSwiftApi import CoreLocation
Use the following code with your API key to initialize the API:
# Using the Public API: let api = What3WordsV4(apiKey: "YourApiKey")
# Using the API Server: let api = What3WordsV4(apiKey: "YourApiKey", apiUrl: "https://api.yourserver.com")
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 = What3WordsV4(apiKey: "YourApiKey", apiUrl: "https://api.yourserver.com", customHeaders: ["x-header-1":"value-1", "x-header-2":"value-2"])
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 is a problem with any call, it will be indicated by the error object.
This function converts coordinates (expressed as latitude and longitude) to a what3words address.
More information about ConvertTo3wa
, including returned results is available in the what3words REST API documentation.
Find the words for (51.484463, -0.195405
):
let coords = CLLocationCoordinate2D(latitude: 51.484463, longitude: -0.195405) api.convertTo3wa(coordinates: coords, language: W3WApiLanguage(locale: "en")) { square, error in print(square?.words ?? "") }
This function converts a what3words address to a position, expressed as coordinates of latitude and longitude.
It takes the words parameter as a string of a what3words 'table.book.chair'
More information about ConvertToCoordinates
, including returned results is available in the what3words REST API documentation.
Find the words for ///prom.cape.pump
:
api.convertToCoordinates(words: "prom.cape.pump") { square, error in print(square?.coordinates ?? "") }
When presented with a what3words address which may be incorrectly entered, AutoSuggest returns a list of potential correct 3 word addresses. It needs the first two words plus at least the first character of the third word to produce suggestions.
This method provides corrections for mis-typed words (including plural VS singular), and words being in the wrong order.
Optionally, clipping can narrow down the possibilities, and limit results to:
This dramatically improves results, so we recommend that you use clipping if possible.
To improve results even further, set the Focus
to user’s current location. This will make AutoSuggest
return results which are closer to the user.
More information about AutoSuggest
, including returned results is available in the what3words REST API documentation.
Code example for an AutoSuggest basic call, 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 ?? "")") } }
Code example an AutoSuggest 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 ?? "") }
Code example AutoSuggest, 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).clip(to: W3WApiCountry(code: "GB")) api.autosuggest(text: "flottons.annulons.garço", options: options) { (suggestions, error) in print(suggestions ?? "") }
Code example AutoSuggest, 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.
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 file.
// make a microphone let microphone = W3WMicrophone() // call autosuggest api.autosuggest(audio: microphone, options: .voiceLanguage(W3WApiLanguage(locale: "en"))) { suggestions, error in for suggestion in suggestions ?? [] { print(suggestion.words ?? "no suggestions") } }
Also, W3WMicrophone
has a callback closure W3WMicrophone.volumeUpdate: (Double) -> ()
that provides amplitude information useful for animating user feedback. See the Voice API example, and more information is available in the Voice API readme file.
Grid section returns a section of the what3words 3m x 3m grid as a set of horizontal and vertical lines covering the requested area, which can then be drawn onto a map.
The requested box must not exceed 4km from corner to corner, or a BadBoundingBoxTooBig
error will be returned.
More information about GridSection
, including returned results is available in the what3words REST API documentation.
Get a grid for 52.207988,0.116126
) in the south west, and 52.208867,0.117540
in the north east:
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") }
This function returns the currently supported languages. It will return the two letter code, and the name of the language both in that language and in English.
More information about AvailableLanguages
, including returned results is available in the what3words REST API documentation.
api.availableLanguages() { (languages, error) in for language in languages ?? [] { print(language.code) } }
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 ?? "") } }
W3WError
enum and the voice autosuggest
call returns a W3WVoiceError
enum.This section introduces RegEx functions that can assist with checking and finding possible what3words addresses in strings. The three main functions covered are:
isPossible3wa
– Match what3words address format;findPossible3wa
– Find what3words address in Text;isValid3wa
– Verify a what3words address with the API;Our API wrapper RegEx function “isPossible3wa
” can be used used to detect if a text string (like “filled.count.soap
“) in the format of a what3words address without having to ask the API. This functionality checks if a given string could be a what3words address. It returns true if it could be, otherwise false.
Note: This function checks the text format but not the validity of a what3words address. Use isValid3wa
to verify validity.
import W3WSwiftApi import CoreLocation func main() { // Initialize the What3Words API with your API key let api = What3WordsV4(apiKey: "YOUR_API_KEY") // Example what3words addresses let addresses = ["filled.count.soap", "not a 3wa", "not.3wa address"] // Check if the addresses are possible what3words addresses for address in addresses { let isPossible = api.isPossible3wa(text: address) print("Is '\(address)' a possible what3words address? \(isPossible)") } } main()
true
false
false
Our API wrapper RegEx function “findPossible3wa
” can be used to detect a what3words address within a block of text, useful for finding a what3words address in fields like Delivery Notes
. For example, it can locate a what3words address in a note like “Leave at my front door ///filled.count.soap
”. The function will match if there is a what3words address within the text. If no possible addresses are found, it returns an empty list.
Note:
isValid3wa
to verify validity.Vietnamese (VI)
due to spaces within words.import W3WSwiftApi import CoreLocation func main() { // Initialize the what3words API with your API key let apiKey = "YOUR_API_KEY" let api = What3WordsV4(apiKey: apiKey) // Example texts let texts = [ "Please leave by my porch at filled.count.soap", "Please leave by my porch at filled.count.soap or deed.tulip.judge", "Please leave by my porch at" ] // Check each text for possible what3words addresses for text in texts { let possibleAddresses = api.findPossible3wa(text: text) print("Possible what3words addresses in '\(text)': \(possibleAddresses)") } } main()
['filled.count.soap']
['filled.count.soap', 'deed.tulip.judge']
[]
Our API wrapper RegEx function “isValid3wa
” can be used to determine if a string is a valid what3words address by checking it against the what3words RegEx filter and verifying it with the what3words API.
import W3WSwiftApi import CoreLocation func main() { // Initialize the what3words API with your API key let apiKey = "YOUR_API_KEY" let api = What3WordsV4(apiKey: apiKey) // Example addresses let addresses = [ "filled.count.soap", "filled.count.", "coding.is.cool" ] // Check if the addresses are valid what3words addresses for address in addresses { api.isValid3wa(words: address) { result in if result == true { print("'\(address)' is a valid what3words address") } else { print("'\(address)' is NOT a valid what3words address") } } } } main()
True
False
False
Also make sure to replace <YOUR_API_KEY>
with your actual API key. These functionalities provide different levels of validation for what3words addresses, from simply identifying potential addresses to verifying their existence on Earth.
If you encounter errors or issues related to convert-to-coordinate requests while using the Free plan, please check the network panel for the following error message Error 402 payment required
and its response, indicating the need to upgrade to a higher plan:
{ "error": { "code": "QuotaExceeded", "message": "Quota Exceeded. Please upgrade your usage plan, or contact support@what3words.com" } }
For more information, visit our API plans page. If you need further assistance, contact support@what3words.com.
A complete example using AutoSuggest to find a place and convertToCoordinates
to find it’s coordinates:
W3wGeocoder.setup(with: "<Secret API Key>") let france = ClipToCountry(country: "FR") let place = Focus(focus: CLLocationCoordinate2D(latitude: 48.856618, longitude: 2.3522411)) let count = NumberResults(numberOfResults: 4) // Find some suggestions for a partial address W3wGeocoder.shared.autosuggest(input: "freshen.overlook.clo", options: france, place, count) { (suggestions, error) in // if there was an error, print it if let e = error { print(e.code, e.message) // on success print the results } else { for suggestion in suggestions ?? [] { print("\(suggestion.words) is near \(suggestion.nearestPlace) - Country Code:\(suggestion.country)") } } // Find coordinates for the first suggestion if let suggestion = suggestions?.first { print("\nFinding the coordinates for: \(suggestion.words)") W3wGeocoder.shared.convertToCoordinates(words: suggestion.words) { (place, error) in // if there was an error, print it if let e = error { print(e.code, e.message) // on success print the result } else if let p = place { print("The coordinates for \(p.words) are (\(p.coordinates.latitude),\(p.coordinates.longitude))") } } } }