我正在制作一个自定义键盘,我想在容器应用程序中构建一个资产(特别是一个 trie 字典),然后在键盘扩展通过共享容器启动时访问它。为此,我从这个相当基本的课程开始:
class Person: NSObject, NSCoding {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
required init(coder decoder: NSCoder) {
self.name = decoder.decodeObject(forKey: "name") as? String ?? ""
self.age = decoder.decodeInteger(forKey: "age")
}
func encode(with coder: NSCoder) {
coder.encode(name, forKey: "name")
coder.encode(age, forKey: "age")
}
}
伟大的。我已经设置了共享容器,并在容器应用程序的 ViewController 的 viewDidLoad 函数中加载了共享容器(一些测试变量和自定义对象):
let shared = UserDefaults(suiteName: "group.test_keyboard")
shared!.set("test", forKey:"key_string")
shared!.set(false, forKey:"key_boolean")
shared!.set(34, forKey:"key_int")
let newPerson = Person(name: "Joe", age: 10)
let encodedData = NSKeyedArchiver.archivedData(withRootObject: newPerson)
shared!.set(encodedData, forKey: "people")
为了测试它,我在 viewWillAppear 中添加了以下代码:
let shared = UserDefaults(suiteName: "group.test_keyboard")
let test_string = shared?.string(forKey: "key_string")
if(test_string != nil){
print("string-\(test_string!)")
}
else{
print("nil")
}
// retrieving a value for a key
if let data = shared?.data(forKey: "people"){
let test_person = NSKeyedUnarchiver.unarchiveObject(with: data) as? Person
print("-\(test_person!.name)") // Joe
let data_size = String(data.count)
print("-\(data_size)")
} else {
print("There is an issue")
}
一切检查都很好。但是当我进入 KeyboardViewController 并尝试访问时,检索简单的字符串可以正常工作:
let shared = UserDefaults(suiteName: "group.test_keyboard")
shared?.synchronize()
let test_string = shared?.string(forKey: "key_string")
if(test_string != nil){
(textDocumentProxy as UIKeyInput).insertText(test_string!)
}
else{
(textDocumentProxy as UIKeyInput).insertText("nil")
}
但是,如果我尝试访问自定义对象 Person,如下所示:
if let data = shared?.data(forKey: "people") {
(textDocumentProxy as UIKeyInput).insertText("found")
(textDocumentProxy as UIKeyInput).insertText(String(data.count))
let myPeople = NSKeyedUnarchiver.unarchiveObject(with: data) as? Person
}
我因以下错误响应而崩溃:
2017-05-10 14:34:46.938253-0700 test_keyboard[3196:857207] viewServiceDidTerminateWithError:: Error Domain=_UIViewServiceInterfaceErrorDomain Code=3 "(null)" UserInfo={Message=Service Connection Interrupted}
数据就在那里,如果我在两侧进行简单的 data.count 检查,它的大小相同(269)。如果我注释掉 NSKeyedUnarchiver 行,就没有问题,所以我确定这就是问题所在。当它在容器应用程序中正常工作时,到底发生了什么导致它在键盘扩展中崩溃?