LoginSignup
2
2

More than 1 year has passed since last update.

【Swift】サードパーティ製キーボードの使用を検知する

Last updated at Posted at 2022-12-14

はじめに

アプリ内で機密な情報を扱う際にサードパーティ製キーボードを使われたくありません。
現在使用されているキーボードがサードパーティ製か判定できるようにしてみました。

サンプルアプリ

Simulator Screen Recording - iPhone 14 - 2022-12-14 at 20 01 01

実装

View

import SwiftUI

struct ContentView: View {
    @StateObject var viewModel = ViewModel()
    var body: some View {
        VStack {
            Text(viewModel.keyboard ? "サードパーティ製キーボードを使用中です" : "標準キーボードです")
            TextField("テキストフィールド", text: $viewModel.text)
                .textFieldStyle(.roundedBorder)
        }
        .padding()
    }
}

ViewModel

import Combine
import UIKit

final class ViewModel: ObservableObject {
    @Published var text: String = ""

    @Published var keyboard: Bool = false

    private let notificationCenter = NotificationCenter.default

    private var cancellable = Set<AnyCancellable>()

    init() {
        notificationCenter.publisher(for: UIResponder.keyboardWillShowNotification)
            .sink { [weak self] _ in
                guard let self else { return }
                self.keyboard = self.isSystemKeyboard()
            }
            .store(in: &cancellable)
    }

    private func isSystemKeyboard() -> Bool {
        let modes = UITextInputMode.activeInputModes
        let displayedModes = modes.filter { $0.value(forKey: "isDisplayed") as? Int == 1 }
        guard let className = displayedModes.first?.superclass?.description() else { return false }
        return className == "UIKeyboardInputMode"
    }
}

UITextInputModeUIKeyboardInputModeで判定したかったのですがプライベートクラス?で使えなかったので文字列に変換して判定しています。

おわり

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2