Custom Keyboard Extensions: Getting Started
Custom keyboard extensions give you the ability to provide keyboards to apps outside of your own. In this tutorial, you’ll walk through creating a custom keyboard extension with advanced features like autocomplete. By Eric Cerney.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Custom Keyboard Extensions: Getting Started
35 mins
Requesting Open Access
In order to do more advanced things from a keyboard extension, you'll need to request those privileges from the user. Open Access is a permission that the user can choose to allow or disallow. It gives your extension a number of capabilities, including:
- Location Services and Address Book, including names, places, and phone numbers.
- Keyboard and containing app can employ a shared container which allows features like iCloud and In-App Purchases.
- Network access for connecting with web services.
- Ability to edit keyboard’s custom autocorrect lexicon via the containing app.
But as Uncle Ben once said, "with great power comes great responsibility." It's up to you to safely handle this sensitive user data.
To get a taste of this power, you'll request access to the user's location from the keyboard extension. Why would a keyboard need the user's location? Well, Morse code is most commonly associated with SOS messages when in distress. It would be great to automatically insert the current location after typing "SOS"!
The first thing you'll need is the user's location. You'll use the Core Location framework to do this. Add the following import to the top of KeyboardViewController.swift:
import CoreLocation
Next, add a property to store current user location under currentWord
:
var currentLocation: CLLocation?
To set this property, you'll use the CLLocationManagerDelegate
protocol. Add the following extension to the bottom of the file:
// MARK: - CLLocationManagerDelegate
extension KeyboardViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
currentLocation = locations.first
}
}
Updates to the user's location trigger a call to this method. To start location updates you'll need to create a CLLocationManager
instance. Add the following property under currentLocation
:
let locationManager = CLLocationManager()
To have locationManager
start updating the location, you'll have to set up some properties. Add the following code to the end of viewDidLoad()
:
locationManager.requestWhenInUseAuthorization()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 100
locationManager.startUpdatingLocation()
This tells the location manager object to only generate location updates while the keyboard is in use.
Note: For more on using CoreLocation to access location data, check out the Apple documentation.
Note: For more on using CoreLocation to access location data, check out the Apple documentation.
The last thing to do is insert the current location after typing the "SOS" message. Replace the current definition of insertCharacter(_:)
with this new definition:
func insertCharacter(_ newCharacter: String) {
if newCharacter == " " {
// 1
if currentWord?.lowercased() == "sos",
let currentLocation = currentLocation {
// 2
let lat = currentLocation.coordinate.latitude
let lng = currentLocation.coordinate.longitude
textDocumentProxy.insertText(" (\(lat), \(lng))")
} else {
// 3
attemptToReplaceCurrentWord()
}
}
textDocumentProxy.insertText(newCharacter)
}
Here's what this does:
- You check if the current word is "sos" and that you have the user's location.
- You insert the current latitude and longitude of the user into the text input view.
- If the current word isn't "sos" or you have no location information, then do as you did before and attempt to replace the current word.
It's time to see if your old-school-distress-signal-meets-modern-tech mechanism works. Build and run the keyboard extension in Safari and type out "sos".
Cheat Sheet:
• • • space – – – space • • • space space
Andddd nothing... That's a bummer. Check the console, and you'll see something like this:
Of course! You're missing some privacy settings in the keyboard property list.
Open Info.plist from within the MorseKeyboard folder. Select Bundle version and click the + symbol to add a new key-value pair.
Type NSLocationWhenInUseUsageDescription for the key and use whatever user friendly message you'd like for requesting access as the value.
Note: At this point, you could technically run the extension on the simulator and see a successful SOS location. There's a bug on the iOS Simulator where you're able to access this data without requesting open access.
Note: At this point, you could technically run the extension on the simulator and see a successful SOS location. There's a bug on the iOS Simulator where you're able to access this data without requesting open access.
Next, expand NSExtension and then NSExtensionAttributes to see the options available to your keyboard extension.
Each of these settings are pretty self explanatory, but if you'd like to learn more about them, check out the Apple documentation
To request open access to get user location data, change the value of RequestsOpenAccess to YES. This means that when installing the keyboard, your users can decide whether to allow access.
Since you've already installed the keyboard, you'll have to give it access manually. Build and run the extension to push these latest changes to your device.
Minimize the app and go to Settings ▸ General ▸ Keyboard ▸ Keyboards ▸ MorseKeyboard and switch the toggle on. Tap Allow on the alert to give full access to your keyboard.
Build and run the extension in Safari one last time. After switching to the keyboard you'll be prompted to allow access to location data. Tap Allow and give "sos" another try.
And there it is! The keyboard is successfully accessing your current location and inserting it into the text input view!
Where To Go From Here?
You can download the final project using the link at the top or bottom of this tutorial.
With this newfound keyboard extension knowledge, you're well on your way to making something truly useful for the world.
This only scratches the surface of all the functionality you could add to a keyboard extension. If you want a deeper dive, check out the Apple Custom Keyboard documentation and Chapter 14 of iOS 8 by Tutorials.
Thanks for following along. As always, if you have any questions or comments on this tutorial, feel free to join the discussion below!