Last active
August 29, 2015 14:22
-
-
Save mojtabacazi/9ff7a2316bdff2cfe728 to your computer and use it in GitHub Desktop.
Detecting language in iOS using NSLinguisticTagger / NSSpellChecker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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