I would like to access a bluetooth device from within a Custom Keyboard Extension
.
However the CBCentralManager
will always fall into a .unsupported
state. I enabled RequestsOpenAccess
in info.plist > NSExtension
.
Does anyone else faced the same issue?
My code is as follows. It's based on Apples default Custom Keyboard Extension
target code.
class KeyboardViewController: UIInputViewController {
@IBOutlet var nextKeyboardButton: UIButton!
internal var manager: BLManager?
override func viewDidLoad() {
super.viewDidLoad()
// Perform custom UI setup here
self.nextKeyboardButton = UIButton(type: .system)
self.nextKeyboardButton.setTitle(NSLocalizedString("Next Keyboard", comment: "Title for 'Next Keyboard' button"), for: [])
self.nextKeyboardButton.sizeToFit()
self.nextKeyboardButton.translatesAutoresizingMaskIntoConstraints = false
self.nextKeyboardButton.addTarget(self, action: #selector(handleInputModeList(from:with:)), for: .allTouchEvents)
self.view.addSubview(self.nextKeyboardButton)
self.nextKeyboardButton.leftAnchor.constraint(equalTo: self.view.leftAnchor).isActive = true
self.nextKeyboardButton.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
print("> BL - Keyboard")
manager = BLManager.shared
}
override func viewWillLayoutSubviews() {
self.nextKeyboardButton.isHidden = !self.needsInputModeSwitchKey
super.viewWillLayoutSubviews()
}
}
With a corresponding BLManager
object.
internal class BLManager: NSObject, CBCentralManagerDelegate {
public static var shared: BLManager = BLManager()
public var manager: CBCentralManager
override init() {
manager = CBCentralManager(delegate: nil, queue: nil)
super.init()
manager.delegate = self
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
manager.scanForPeripherals(withServices: nil, options: nil)
}
print("> BL \(central.state)")
}
}