作爲我正在開發的自定義鍵盤的用戶自定義體驗的一部分,我想知道我的自定義鍵盤當前是否對從內部輸入的文本處於活動狀態包含(父)應用程序。檢測自定義鍵盤是否從鍵盤的容器應用程序當前處於活動狀態
有沒有辦法做到這一點,類似於你可以如何discover whether the keyboard is installed?
作爲我正在開發的自定義鍵盤的用戶自定義體驗的一部分,我想知道我的自定義鍵盤當前是否對從內部輸入的文本處於活動狀態包含(父)應用程序。檢測自定義鍵盤是否從鍵盤的容器應用程序當前處於活動狀態
有沒有辦法做到這一點,類似於你可以如何discover whether the keyboard is installed?
做了一些進一步的研究後,我還沒有找到一種方法來完成這一點。
但是,如果任何人處於相同的情況,這裏是我暫時採用的解決方法。
1.檢測鍵盤變化
你的鍵盤會不會自動安裝後的活動的鍵盤,所以如果你提示用戶換鍵盤,你可以檢測與UITextInputCurrentInputModeDidChangeNotification
這種變化。不能保證用戶換成了鍵盤,而不是像表情符號鍵盤那樣,但這是我選擇製作的假設。
可以使用它作爲這樣:
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidChange:) name:UITextInputCurrentInputModeDidChangeNotification object:nil];
}
- (void)keyboardDidChange:(NSNotification *)notification {
// keyboard changed, do your thing here
}
2.共享應用程序組
另一種方式來做到這將是建立一個共享的應用程序組,並寫入Shared User Defaults
從你的鍵盤一旦被激活。然後在您的包含應用程序中,您可以將NSTimer
設置爲運行循環,您可以檢查是否已寫入用戶默認值。例如,這可能與當前日期類似,並且檢查是否已經足夠近(幾秒鐘內)以指示最近的更改。
我沒有使用它,因爲它增加了一些開銷,但它會比鍵盤更改通知更加萬無一失(從用戶的角度來看)。
下面是一個如何完成它的例子。
KeyboardViewController.m
:
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.bundleID"];
[sharedDefaults setObject:[NSDate date] forKey:@"lastOpenDate"];
[sharedDefaults synchronize];
}
CompanionViewController.m
:
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *runloop = [NSTimer scheduledTimerWithTimeInterval:0.5 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSUserDefaults *sharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.bundleID"];
[sharedDefaults synchronize];
NSDate *lastOpenDate = [sharedDefaults objectForKey:@"lastOpenDate"];
if (lastOpenDate != nil && [lastOpenDate timeIntervalSinceNow] > -1.0) {
[timer invalidate];
// keyboard changed, do your thing here
}
}
[runloop fire];
}