Albert Renshaw
Albert Renshaw

Reputation: 17882

Detect if Custom Keyboard has been installed

I've read through the documentation and can't seem to find any method of how can I detect if a custom keyboard has been installed in settings>general>keyboards?

Does anyone know of any?

Upvotes: 4

Views: 2091

Answers (3)

harryngh
harryngh

Reputation: 1859

This works for me

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
}

Upvotes: 1

v.ng
v.ng

Reputation: 794

Here is the Swift version of @Matt solution:

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")
    }
}

Upvotes: 0

Matt
Matt

Reputation: 2359

This is possible with NSUserDefaults. Just retrieve the standardUserDefaults object which contains an array of all the keyboards the user has installed for key "AppleKeyboards". Then check if the array contains the bundle identifier for your keyboard extension.

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");
}

Upvotes: 9

Related Questions