UITextDocumentProxy documentContextAfterInput Not Returning Full Text After Cursor in Swift

34 views Asked by At

I am working on an iOS custom keyboard extension and using UITextDocumentProxy to read the context before and after the cursor position. I've encountered a problem where documentContextAfterInput only returns the text until the end of the line where the cursor is placed, rather than all subsequent text.

Here is the snippet of my code that handles the context reading:

    // Reading the context before the cursor position works fine
while let previousContext = textProxy.documentContextBeforeInput, !previousContext.isEmpty {
    context = previousContext + context
    startingOffset += previousContext.count
    textProxy.adjustTextPosition(byCharacterOffset: -previousContext.count)
    try? await Task.sleep(nanoseconds: 50_000_000)
}

// Trying to adjust the cursor back to its original position after reading
textProxy.adjustTextPosition(byCharacterOffset: context.count)
try? await Task.sleep(nanoseconds: 1000_000_000)

// Reading the context after the cursor is not returning the full text
while var nextContext = textProxy.documentContextAfterInput, !nextContext.isEmpty {
    forwardContextCount += 1
    context += nextContext
    textProxy.adjustTextPosition(byCharacterOffset: nextContext.lengthOfBytes(using: .utf8))
    try? await Task.sleep(nanoseconds: 100_000_000)
    nextContext = textProxy.documentContextAfterInput ?? "no value"
    debugPrint(nextContext)
}

Given the following text:

'Hello nick,

Happy Monday!

Thank you for your response. Hope you are doing well can we meet tomorrow?

Hope to see you tomorrow!!

Best Regards Umair khan

Sent from my iPhone'

When I place the cursor before "Hello", documentContextAfterInput only reads "Hello nick," and does not include any text after the new line.

What I've tried:

Ensuring adjustTextPosition(byCharacterOffset:) is correctly used to navigate the cursor position. Adding sleep delays to allow for any asynchronous updates. My questions are:

Why does documentContextAfterInput not return the full text following the cursor, particularly after new lines?

Is there a limitation with UITextDocumentProxy's documentContextAfterInput that I am not aware of?

How can I ensure that all text after the cursor is read, regardless of new lines or other formatting?

Any insights or suggestions for debugging this behavior would be greatly appreciated.

0

There are 0 answers