简体   繁体   English

Swift键盘扩展程序更新NSUserDefaults

[英]Swift Keyboard Extension update NSUserDefaults

I'm trying to make an iOS keyboard extension but I'm having trouble syncing/updating the data from the containing app to the extension. 我正在尝试制作iOS键盘扩展程序,但无法同步/将数据从包含的应用程序同步到该扩展程序。

As the doc states, I'm using 正如文档所述,我正在使用

NSUserDefaults *mySharedDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.example.domain.MyShareExtension"];
[mySharedDefaults setObject:theAccountName forKey:@"lastAccountName"];

That works perfectly. 那很好。 Before launching the keyboard in the containing app, I use that, and in the keyboard's viewdidLoad I check NSUserDefault and everything works fine. 在包含应用程序中启动键盘之前,请先使用它,然后在键盘的viewdidLoad中检查NSUserDefault,一切正常。

The problem is if in my containing app I update my NSUserDefaults, how can I know in my keyboard app that the NSUserDefaults have been updated. 问题是,如果在我的包含应用程序中更新了NSUserDefaults,如何在键盘应用程序中知道NSUserDefaults已更新。

I tried KVO, does not work. 我尝试了KVO,不起作用。 I tried NSUserDefaultsStandard, with NSUserDidChangeNotification, does not work. 我尝试使用NSUserDidChangeNotification的NSUserDefaultsStandard无法正常工作。 NSUserDefaultsStandard does not work at all for the keyboard extension. NSUserDefaultsStandard对于键盘扩展完全不起作用。

I was thinking of using an NSTimer in my keyboard extension, and check the NSUserDefaults every X ms. 我当时想在键盘扩展中使用NSTimer,并每隔X ms检查一次NSUserDefaults。 But it's overkill. 但这太过分了。

I know it's possible since apps are doing it in the AppStore. 我知道这是可能的,因为应用程序正在AppStore中进行操作。 BrightKey or CoolKey change the keyboard design from the containing app. BrightKey或CoolKey从包含的应用程序更改键盘设计。 So they definitely have a callback or something to update their data. 因此,他们肯定有回调或更新数据的方法。

Thanks in advance for anyone coming up with a clean solution. 预先感谢任何提出干净解决方案的人。

您可以在每次键盘输入和包含应用加载时向共享用户默认值读取/写入值。

Mt trick is: 绝招是:

Just add a UITextField to your containing app, and set the Hidden property On , so the textfield is invisible. 只需将UITextField添加到包含的应用程序中,然后将Hidden属性设置为On ,则文本字段将不可见。

After user selected any theme, just call textView.becomeFirstResponder() so it seems that you have loaded keyboard after user selected theme. 用户选择任何主题之后,只需调用textView.becomeFirstResponder()这样看来您在用户选择主题之后就已经加载了键盘。 after user selected another theme, just call textView.resignFirstResponder() and wait for about 0.6 seconds (so NSUserDefaults updates) and then again call textView.becomeFirstResponder() and your keyboard will load with new theme! 用户选择另一个主题后,只需调用textView.resignFirstResponder()并等待约0.6秒(以便NSUserDefaults更新),然后再次调用textView.becomeFirstResponder textView.becomeFirstResponder() ,您的键盘将加载新主题! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM