Currently, I am working on a custom Swift keyboard and using the Keyboard Kit framework.
I have researched various solutions, and this one is the best
But after I implemented this code for Swift 5, it works when I placed cursor end of the text.
Code:
let readerQueue = DispatchQueue(label: "com.customKeyboard.reader.test")
func foo() {
readerQueue.async {
self.keyboardService.fullDocumentContext()
}
}
func fullDocumentContext() {
guard let textProxy else { return }
var startingOffset = 0
var context = ""
while let previeosContext = textProxy.documentContextBeforeInput, !previeosContext.isEmpty {
context = previeosContext + context
startingOffset += previeosContext.count
textProxy.adjustTextPosition(byCharacterOffset: -previeosContext.count)
Thread.sleep(forTimeInterval: 0.01)
}
textProxy.adjustTextPosition(byCharacterOffset: context.count)
Thread.sleep(forTimeInterval: 0.01)
while let nextContext = textProxy.documentContextAfterInput, !nextContext.isEmpty {
context += nextContext
textProxy.adjustTextPosition(byCharacterOffset: nextContext.count)
Thread.sleep(forTimeInterval: 0.01)
}
print(context)
}
If I place the cursor in the middle of the text and retrieve data from before the cursor, then move the cursor back and try to iterate forward, it only works once. I do not figure it out why it can not iterate forward.