On an iOS device, using the native keyboard (US english and "Predictive" turned on), if you write eg:
"Have a " (with a space at the end)
It will suggest three contextually relevant next-word-predictions on the bar at the top of the keyboard:
good great nice
I want to make use of this next-word prediction logic on iOS, but it turns out that I can only get it to work on OS X, where it's super simple.
So here is a tiny command line app that does exactly what I want (allthough only on OS X):
import AppKit
let str = "Have a "
let rangeForEndOfStr = NSMakeRange(str.utf16.count, 0)
let spellChecker = NSSpellChecker.sharedSpellChecker()
let completions = spellChecker.completionsForPartialWordRange(
rangeForEndOfStr,
inString: str,
language: "en",
inSpellDocumentWithTag: 0)
print(completions)
Running that program will print:
Optional(["good", "great", "nice", "lot", "problem", "new", "feeling", "chance", "few", "wonderful", "look", "big", "boyfriend", "better", "very", "job", "bad", "lovely", "crush", "blessed"])
Note that the first three words are exactly the same as those displayed by the native (predictive) iOS keyboard. So it works (at least on OS X)!
(It works by giving .completionsForPartialWordRange an zero-length range located at the end of the string (where the next word would go), rather than a range containing a partial word, allthough I guess you could say that a non-existing word is also a partial word.)
But trying the same approach on iOS (using UITextChecker instead of NSSpellChecker, etc.) does not work:
let str = "Have a "
let rangeForEndOfStr = NSMakeRange(str.utf16.count, 0)
let spellChecker = UITextChecker()
print(UITextChecker.availableLanguages())
let completions = spellChecker.completionsForPartialWordRange(
rangeForEndOfStr,
inString: str,
language: "en_US") // ( <-- .availableLanguages() says "en_US" on iOS and "en" on OS X. )
print(completions)
(this code can be put in the viewDidLoad of the ViewController of an otherwise empty Single View iOS app.)
Run the iOS app and it will just print nil. : (
Turns out that UITextChecker's .completionsForPartialWordRange (contrary to NSSpellChecker's) simply returns nil if the range has zero length. I have tried all day to find any other way to get next-word-of-sentence-predictions/-suggestions/-completions on iOS but failed.
(NOTE: I have no problem getting UITextChecker to return completions of partially entered wods, ie where the range is not empty, but contains partially written word(prefixe)s, allthough the resulting completions are not sorted so that the more probable comes first, as the documentation says. They are actually just sorted alphabetically ... Anyway, what I want is something else: Given a partially written sentence containing only complete words, I want a list of probable-next-word-in-sentence-completions, exactly as examplified by my OS X example and the native iOS keyboard above.)
So, how do I write a working iOS-version of the OS X example above?