Skip to content

Instantly share code, notes, and snippets.

@mojtabacazi
Last active August 29, 2015 14:22
Show Gist options
  • Save mojtabacazi/9ff7a2316bdff2cfe728 to your computer and use it in GitHub Desktop.
Save mojtabacazi/9ff7a2316bdff2cfe728 to your computer and use it in GitHub Desktop.
Detecting language in iOS using NSLinguisticTagger / NSSpellChecker
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:@[NSLinguisticTagSchemeLanguage, nil] options:0];
[tagger setString:@"Das ist ein bisschen deutscher Text. Bitte löschen Sie diesen nicht."];
NSString *result = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([result isEqualToString:@"und"]) {
// language detection failed
} else {
// result will be standard language abbreviations such as “en”, “fr”, “de”, etc.,
// From Apple's doc: Languages are uniformly described by BCP-47 tags , preferably in canonical form;
}
// Alternative using NSSpellChecker
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);
}];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment