How to get a list of suggestions for a custom keyboard?

430 views Asked by At

I've been trying to figure out a way to get a list of suggestions for a user inputted text (in multiple languages Not English en-US) ,i already found so many talking around questions here ,but no one figured out the whole solution ,so i am trying to execute the following scenario :

1- User typed a letter or more (ex. "Ap")

2- get a list of suggested words (ex. Apple,Apply, ...)

How should i get this list like Custom Keyboard Apps (ex. Swift key)

Thanks in advance.

1

There are 1 answers

0
Vishnu Kumar. S On

Try this one.

+ (void)getSuggestionsFor:(NSString *)word WithCompletion:(void(^)(NSArray *))completion
{
    NSString *prefix = [word substringToIndex:word.length - 1];
    // Won't get suggestions for correct words, so we are scrambling the words
    NSString *scrambledWord = [NSString stringWithFormat:@"%@%@",word, [self getRandomCharAsNSString]];
    UITextChecker *checker = [[UITextChecker alloc] init];
    NSRange checkRange = NSMakeRange(0, scrambledWord.length);
    NSRange misspelledRange = [checker rangeOfMisspelledWordInString:scrambledWord range:checkRange startingAt:checkRange.location wrap:YES  language:@"en_US"];

    NSArray *arrGuessed = [checker guessesForWordRange:misspelledRange inString:scrambledWord language:@"en_US"];
    // NSLog(@"Arr ===== %@",arrGuessed);
    // Filter the result based on the word
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",word];
    NSArray *arrayfiltered = [arrGuessed filteredArrayUsingPredicate:predicate];
    if(arrayfiltered.count == 0)
    {
        // Filter the result based on the prefix
        NSPredicate *newPredicate = [NSPredicate predicateWithFormat:@"SELF BEGINSWITH[c] %@",prefix];
        arrayfiltered = [arrGuessed filteredArrayUsingPredicate:newPredicate];
    }
    completion(arrayfiltered);
}


+ (NSString *)getRandomCharAsNSString {
    return [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a'];
}