iosswiftuitextinput

Getting the currently active keyboard language as NSLocale


I already found a lot of approaches for this but no working solution. Here's what I tried and didn't work.

(1) Simply calling primaryLanguage()

UITextInputMode().primaryLanguage

→ always returns nil :-/

(2) Subscribing to UITextInputCurrentInputModeDidChangeNotification notifications

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "changeInputMode:", name: UITextInputCurrentInputModeDidChangeNotification, object: nil)
}

func changeInputMode(sender : NSNotification) {
    ...?!
}

The notification is getting triggered but it is unclear how I can extract the current language information from the notification.

(3) Using activeInputModes()

let localeIdentifier = UITextInputMode.activeInputModes().first as? UITextInputMode
var locale:NSLocale = NSLocale(localeIdentifier: localeIdentifier.primaryLanguage!)
println("Input Mode Language \(localeIdentifier.primaryLanguage!)")

This always provides the same array of all available keyboards, no information on the actually active one.

How do I get the NSLocale of the currently active keyboard?


Solution

  • You can access the primaryLanguage from every textfield by accessing the textfields textInputMode like that:

    var language = textfield.textInputMode?.primaryLanguage