Detect Language of NSString

后端 未结 6 1058
鱼传尺愫
鱼传尺愫 2020-11-27 11:39

Somebody told me about a class for language recognition in Cocoa. Does anybody know which one it is?

This is not working:

NSSpellCh         


        
6条回答
  •  独厮守ぢ
    2020-11-27 12:31

    You can use -requestCheckingOfString:… instead. NSTextCheckingTypeOrthography attempts to identify the language used in the string, and the completion handler receives an NSOrthography parameter that can be used to get information about the orthography in the string, including its dominant language.

    The following example outputs dominant language = de:

    NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
    [spellChecker setAutomaticallyIdentifiesLanguages:YES];
    NSString *spellCheckText = @"Guten Herr Mustermann. Dies ist ein deutscher Text. Bitte löschen Sie diesen nicht.";
    
    [spellChecker requestCheckingOfString:spellCheckText
        range:(NSRange){0, [spellCheckText length]}
        types:NSTextCheckingTypeOrthography
        options:nil
        inSpellDocumentWithTag:0
        completionHandler:^(NSInteger sequenceNumber, NSArray *results, NSOrthography *orthography, NSInteger wordCount) {
            NSLog(@"dominant language = %@", orthography.dominantLanguage);
    }];
    

提交回复
热议问题