有没有办法确定在“设置”中启用了哪些键盘?
只有启用了中文键盘才能与新浪微博分享,所以如果有中文键盘,我只想显示“新浪微博”操作表按钮。
答案 0 :(得分:4)
感谢盖伊的评论,有更好的方法可以做到这一点。我已更新自己的代码以使用以下内容:
NSArray *keyboards = [UITextInputMode activeInputModes];
for (UITextInputMode *mode in keyboards) {
NSString *name = mode.primaryLanguage;
if ([name hasPrefix:@"zh-Han"]) {
// One of the Chinese keyboards is installed
break;
}
}
Swift :( 注意:由于UITextInputMode activeInputModes
的声明错误而在iOS 9.x下损坏。请参阅this answer以获取解决方法。)
let keyboards = UITextInputMode.activeInputModes()
for var mode in keyboards {
var primary = mode.primaryLanguage
if let lang = primary {
if lang.hasPrefix("zh") {
// One of the Chinese keyboards is installed
break
}
}
}
旧方法:
我不知道App Store应用程序中是否允许这样做,但您可以这样做:
NSArray *keyboards = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleKeyboards"];
for (NSString *keyboard in keyboards) {
if ([keyboard hasPrefix:@"zh_Han"]) {
// One of the Chinese keyboards is installed
}
}
如果用户的区域设置只有默认键盘,则可能没有AppleKeyboards
键的条目。在这种情况下,您可能需要检查用户的区域设置。如果该地区是针对中国的,那么你可以假设他们有一个中文键盘。
答案 1 :(得分:-1)
此代码非常有助于我识别来自父应用程序本身的设备设置中是否激活了键盘扩展程序:
//Put below function in app delegate...
public func isKeyboardExtensionEnabled() -> Bool {
guard let appBundleIdentifier = NSBundle.mainBundle().bundleIdentifier else {
fatalError("isKeyboardExtensionEnabled(): Cannot retrieve bundle identifier.")
}
guard let keyboards = NSUserDefaults.standardUserDefaults().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
}
// Call it from below delegate method to identify...
func applicationWillEnterForeground(_ application: UIApplication) {
if(isKeyboardExtensionEnabled()){
showAlert(message: "Hurrey! My-Keyboard is activated");
}
else{
showAlert(message: "Please activate My-Keyboard!");
}
}
func applicationDidBecomeActive(_ application: UIApplication) {
if(isKeyboardExtensionEnabled()){
showAlert(message: "Hurrey! My-Keyboard is activated");
}
else{
showAlert(message: "Please activate My-Keyboard!");
}
}