How to detect that textDidChange: on a UISearchBar was caused by dictation

I am currently faced with a problem related to UISearchBar and dictation support. I have to call some filter logic when the text of the search bar changes. This logic must be triggered either by a change that was made using the keyboard or dictation.

Now here is my problem: if I end the dictation in the search bar, the textDidChange method starts immediately (while speech recognition is in textDidChange ). After recognition, the method starts again with the correct line.

How to determine that the first method call was initiated by the beginning of speech recognition? Because I have to avoid doing my logic in this case.

I already tried to check the searchText parameter, which is passed to the method. But the results are seemingly suspicious.

If I add this code to searchBar:textDidChange:

 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { NSLog(@"SearchText [%@] - SearchTextLength [%i] - SearchTextEquals [%i]", searchText, searchText.length, [searchText isEqualToString:@""]); } 

I get this result:

 SearchText [๏ฟผ] - SearchTextLength [1] - SearchTextEquals [0] 

I am stuck at this point. How can searchText be [] (empty) but has a length of 1? Is there any other way to detect that speech recognition still works?

+4
source share
2 answers

I had the same problem: find that the speech dictation is still working and is processing the speech input.

This is exactly the same as you describe: from textDidChange you get an empty NSString with length = 1

In my case, my solution was to take the first char of the text (if available) and check its integer value. Apparently, the value of โ€œvoice input processingโ€ is always -17 ,

I know this is not an ideal solution, but it works. If anyone has a better solution, share it :)

 - (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{ BOOL atLeastOneChar = searchText.length > 0; BOOL speechRecognitionOngoing; if (atLeastOneChar) { // Checking if the user used the dictation feature. // A char of value -17 is always returned as text while processing the voice. // So if the first char is == -17 it means the dictationg is going on. const char firstChar = *text.UTF8String; NSInteger processingDictationSpeechChar = -17; if (firstChar == processingDictationSpeechChar) { // --> speech recognition is ongoing! speechRecognitionOngoing = YES; } } } 
+3
source

You can detect a dictation in [UITextInputMode currentInputMode].primaryLanguage; with [UITextInputMode currentInputMode].primaryLanguage; - this returns dictation during dictation, because gray overlay with wave during dictation is the keyboard from the point of view of the application. You can also detect the change by listening to UITextInputCurrentInputModeDidChangeNotification .

0
source

Source: https://habr.com/ru/post/1501606/


All Articles