Search code examples
ioskeyboarduitextinput

Why does InsertText from UITextInput breaks keyboard suggestions?


So we recently had an issue with our Keyboard extension showing wrong suggestions in the accompanying app. We found out that the text returned from context (super.textDocumentProxy.documentContextBeforeInput) was all wrong and since its a build in apple component something must go wrong with text insertion. We had following implementation for inserting text:

    if (replaceRange.length > 0) {
        [self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
        [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word
    } else {
        [self.textView insertText:selectedWord];
    }

Would return something like:

There. . .

While the real text would be something like:

There it was. It was a little test. Test of everything.


Solution

  • The issue was found to be with insertText apparently it will properly insert text but the Keyboard context will not be able to read the inserted text. Now the fix was simply to use the replaceCharactersInRange for both insertions (meaning no if / else clause):

    [self.textView.textStorage replaceCharactersInRange:replaceRange withString:selectedWord];
            [textView setSelectedRange:NSMakeRange(newLocation, 0)];  //Place cursor after inserted word
    

    This solved the issue and has made us conclude that insertText doesn't work as intended. Note that this will only be an issue if suggestions are to be used in the text field.