Check if user is using custom keyboard

Viewed 444

Is there a way to check if the user is currently using a custom keyboard? I know how to check all the keyboards but I want to know the exact keyboard that is selected.

Here is how you check which Keyboards are available but how do I know which one the user is currently using?

class func isKeyboardExtensionEnabled() -> Bool {
    guard let keyboards = UserDefaults.standard.dictionaryRepresentation()["AppleKeyboards"] as? [String] else {
        return false
    }
    print("the keyboards are \(keyboards)")
    for keyboard in keyboards {
        if keyboard.contains("KeyboardExtension"){
            return true
        }
    }

    return false
}

The why is I have a view that needs to be the same height as the keyboard. I can get the system height pretty easy just making a textfield the responder and dismissing it before it is seen.

let keyboardFrame: NSValue = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue

But for UIKeyboardWillShow notification the height is incorrect causing the height needed for the fixed height view to be incorrect. It is correct after the 2 or 3 call but for custom keyboards I would like to know to expect erroneous values.

But as more to the example if you want to see the incorrect values here is a controller.

import UIKit
import Foundation
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillAppear(notification:)), name:  UIWindow.keyboardWillShowNotification, object: nil)

        showKeyboard()

    }

    func showKeyboard(){
        let tf = UITextField(frame: .zero)
        self.view.addSubview(tf)
        tf.becomeFirstResponder()

    }

    //MARK: Keyboard
    @objc func keyboardWillAppear(notification: NSNotification){
        //find the extrasafe bottom
        if let userInfo = notification.userInfo as? [String: Any],
            let keyboardFrame: NSValue = userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue{
            let keyboardRectangle = keyboardFrame.cgRectValue
            let keyboardHeight = keyboardRectangle.height
            print("keyboard height is \(keyboardHeight)")
        }
    }

    deinit {
        NotificationCenter.default.removeObserver(self, name: UIWindow.keyboardWillShowNotification, object: nil)
    }
}

The printed output is keyboard height is 335.0 on the iPhone X. if you install Gboard and make it the default keyboard and run the app you will get a print out of keyboard height is 75.0 keyboard height is 216.0 keyboard height is 333.0. I would just love to know to expect these junk values.

0 Answers
Related