Skip to content

Instantly share code, notes, and snippets.

@dasdom
Last active August 23, 2018 14:39
Show Gist options
  • Save dasdom/7278603 to your computer and use it in GitHub Desktop.
Save dasdom/7278603 to your computer and use it in GitHub Desktop.
Language detection in iOS. This code is used to add the language to a post in my ADN client hAppy. This is pubic domain. To with it what every you like!
NSString *languageGuessedString;
if (postString.length < 60) {
languageGuessedString = nil;
} else {
NSArray *componentsArray = [postString componentsSeparatedByString:@" "];
NSMutableString *mutablePostString = [NSMutableString string];
for (NSString *string in componentsArray) {
if ([string rangeOfString:@"@"].location != NSNotFound) {
continue;
}
NSDataDetector *detector = [NSDataDetector dataDetectorWithTypes:NSTextCheckingTypeLink error:nil];
NSUInteger numberOfMatches = [detector numberOfMatchesInString:string options:0 range:NSMakeRange(0, string.length)];
if (numberOfMatches > 0) {
continue;
}
[mutablePostString appendFormat:@"%@ ", string];
}
languageGuessedString = (NSString*)CFBridgingRelease(CFStringTokenizerCopyBestStringLanguage((CFStringRef)mutablePostString, CFRangeMake(0, mutablePostString.length)));
}
NSLog(@"languageGuessedString: %@", languageGuessedString);
NSString *primaryLanguage;
if (languageGuessedString) {
primaryLanguage = languageGuessedString;
} else {
primaryLanguage = [UITextInputMode currentInputMode].primaryLanguage;
}
NSString *languageString;
if ([primaryLanguage isEqualToString:@"zh-Hant"]) {
languageString = @"zh_CN";
} else if ([primaryLanguage isEqualToString:@"zh-Hans"]) {
languageString = @"zh_TW";
} else {
languageString = [[primaryLanguage componentsSeparatedByString:@"-"] objectAtIndex:0];
}
NSLog(@">>>> set language: %@", languageString);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment