我已阅读文档,但似乎找不到任何方法来检测设置>常规>键盘中是否安装了自定义键盘?
有人知道吗?
这可以通过
NSUserDefaults
实现。只需检索 standardUserDefaults
对象,该对象包含用户为“AppleKeyboards”键安装的所有键盘的数组。然后检查数组是否包含键盘扩展的包标识符。
NSArray *keyboards = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleKeyboards"];
NSLog(@"keyboards: %@", keyboards);
// check for your keyboard
NSUInteger index = [keyboards indexOfObject:@"com.example.productname.keyboard-extension"];
if (index != NSNotFound) {
NSLog(@"found keyboard");
}
这对我有用
func isKeyboardExtensionEnabled() -> Bool {
guard let appBundleIdentifier = Bundle.main.bundleIdentifier else {
fatalError("isKeyboardExtensionEnabled(): Cannot retrieve bundle identifier.")
}
guard let keyboards = UserDefaults.standard.dictionaryRepresentation()["AppleKeyboards"] as? [String] else {
// There is no key `AppleKeyboards` in NSUserDefaults. That happens sometimes.
return false
}
let keyboardExtensionBundleIdentifierPrefix = appBundleIdentifier + "."
for keyboard in keyboards {
if keyboard.hasPrefix(keyboardExtensionBundleIdentifierPrefix) {
return true
}
}
return false
}
这是 2023 年 @Matt 解决方案的 Swift 版本,希望对您有所帮助:
if let keyboards = UserDefaults.standard.array(forKey: "AppleKeyboards") as? [String] {
print("keyboards: \(keyboards)")
if let index = keyboards.firstIndex(of: "com.example.productname.keyboard-extension") {
print("found keyboard")
}
}