检测当前输入语言

时间:2016-11-26 17:36:05

标签: swift macos cocoa macos-carbon nssearchfield

我正在构建一个应用程序,允许用户查看世界各地的当地时间。这些信息是使用Google API获取的,并且一切正常,但为了获得最佳效果,我需要指定我想要使用的语言。

显然,在我的情况下,将所需语言设置为用户在键入城市名称时使用的语言是有意义的。在iPhone上这很容易做到,但我无法弄清楚如何在macOS上获得这个语言代码。有人可以帮我吗?

更新

根据Leo的建议,我现在正处于我在碳框架的帮助下获得当前输入的阶段。

for uw in suw:
    # whatever

问题是let source = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() let lang = TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages).assumingMemoryBound(to: NSArray.self).pointee 会返回TISGetInputSourceProperty()。我无法找到将其转换为可读的方法。我认为它是UnsafeMutableRawPointer,但我没有运气试图转换它。有人可以帮忙吗?

2 个答案:

答案 0 :(得分:1)

let source = TISCopyCurrentKeyboardInputSource().takeUnretainedValue()
let value = TISGetInputSourceProperty(source, kTISPropertyInputSourceLanguages)
if (value != nil) {
    var name = Unmanaged<AnyObject>.fromOpaque(value!).takeUnretainedValue() as? String
}

我在这里学习https://github.com/noraesae/kawa/blob/master/kawa/InputSourceManager.swift

答案 1 :(得分:0)

Carbon有TISCopyCurrentKeyboardInputSource(),它为您提供当前语言。

TISInputSourceRef source = TISCopyCurrentKeyboardInputSource(); TISGetInputSourceProperty(source,kTISPropertyInputSourceLanguages));

还有kTISNotifySelectedKeyboardInputSourceChanged分发通知来确定语言何时发生变化。

对于Swift的易用性,请考虑制作一个Objective C包装器,它返回上述API的字符串值。