0

I'm trying to perform a simple task in XCode of checking whether a certain NSString language matches the user's preferred language.

For example, let's say I have a string such as the following:

NSString *englishString = @"Good morning!";
NSString *frenchString = @"Bonjour!";

I know I can get the user device's preferred language using the NSLocaleLanguageCode value, and based on a previous Stack Overflow answer here, I can get the language of the NSString. However, when I compare the two values, the keys don't seem to match. Is there a better way to go about implementing this? Thanks!

The documentation for NSLocaleLanguageCode can be found here and the description for NSLinguisticTagger can be found here. NSLocaleLanguageCode returns an NSString while the tagger, and in particular, the "tagAtIndex" method returns an NSLinguisticTag key.

  • 1
    Update your question with example results. What do you get from `NSLocalLanguageCode` and what do you get using `NSLinguisticTagger`? – rmaddy Jul 31 '18 at 00:44
  • @rmaddy thanks for the suggestion, added links above to the question! – jyangballin Jul 31 '18 at 01:09
  • FYI - I just added [an answer](https://stackoverflow.com/a/51604151/1226963) to [the other question](https://stackoverflow.com/questions/6325073/detect-language-of-nsstring) that makes it much simpler to get the language of a string if you are using iOS 11+/macOS 10.13+. – rmaddy Jul 31 '18 at 01:18

1 Answers1

0

You get a string for both. In Objective-C, NSLinguisticTag is a synonym for NSString *. Simply compare the NSLinguisticTag (really just an NSString) to the NSString you obtained from the locale's language code.

But a simpler solution is to use the dominantLanguageForString: class method of NSLinguisticTagger to easily get the language of a string as an NSString. This is much simpler than using one of the tag... instance methods of NSLinguisticTagger but it does require iOS 11+/macOS 10.13+.

NSLinguisticTag languageTag = ... // tag from NSLinguisticTagger

NSString *languageCode = ... // language from NSLocale

if ([languageCode isEqualToString:languageTag]) {
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579