I am facing a weird issue when sharing a struct array between an app and iMessage Extension.
Here is my code.
struct RecentlyUsed {
var isPreset: Bool?
var imgId: Int?
}
extension RecentlyUsed {
init?(data: NSData) {
if let coding = NSKeyedUnarchiver.unarchiveObject(with: data as Data) as? Encoding {
isPreset = coding.isPreset! as Bool
imgId = coding.imgId!
}
}
func encode() -> NSData {
return NSKeyedArchiver.archivedData(withRootObject: Encoding(self)) as NSData
}
private class Encoding: NSObject, NSCoding {
let isPreset: Bool?
let imgId: Int?
init(_ recentlyUsed: RecentlyUsed) {
self.isPreset = recentlyUsed.isPreset
self.imgId = recentlyUsed.imgId
}
@objc required init?(coder aDecoder: NSCoder) {
self.isPreset = aDecoder.decodeObject(forKey: "isPreset") as? Bool
self.imgId = aDecoder.decodeObject(forKey: "imgId") as? Int
}
@objc func encode(with aCoder: NSCoder) {
aCoder.encode(isPreset, forKey: "isPreset")
aCoder.encode(imgId, forKey: "imgId")
}
}
}
And I created an app group named "group.io.interepid.sharingdata" to share this array and then tested to read and write in my app.
So it works very well.
var recentlyUsedArr: [RecentlyUsed] = []
...
// Code for read
let settings = UserDefaults(suiteName: "group.io.interepid.sharingdata")
if let dataArray = settings?.object(forKey: "data") as? [NSData] {
self.recentlyUsedArr.append(contentsOf: dataArray.map{ RecentlyUsed(data: $0)! })
} else {
}
// Code for write
let settings = UserDefaults(suiteName: "group.io.interepid.sharingdata")
let placeData = self.recentlyUsedArr.map{ $0.encode() }
settings?.set(placeData, forKey: "data")
settings?.synchronize()
But when I read the array in this app's iMessage extension, I got an error.
I used the code the same with app's side.
2017-02-14 10:02:59.648256 Emoji Me[5616:2399759] * Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: '* -[NSKeyedUnarchiver decodeObjectForKey:]: cannot decode object of class (_TtCV7emojime12RecentlyUsedP33_B90A8EFD4225717A6A5C48CD3F99B2FC8Encoding) for key (root); the class may be defined in source code or a library that is not linked' Blockquote *** First throw call stack: (0x18794d1b8 0x18638455c 0x1883f0408 0x1883f05c4 0x1883bc1cc 0x1883bbfa8 0x1883bb168 0x100085ff8 0x100076ec0 0x100076f6c 0x100219068 0x100075f2c 0x100078018 0x18d802924 0x18d8024ec 0x100074048 0x1000737dc 0x10007383c 0x1a34e2edc 0x1867d61fc 0x1867d61bc 0x1867dad68 0x1878fa810 0x1878f83fc 0x1878262b8 0x1892da198 0x18d86d7fc 0x18d868534 0x186a2bcc8 0x186a2d944 0x1885723c4 0x19001e128 0x19001dc90 0x19001e14c 0x1885580d4 0x1868095b8) libc++abi.dylib: terminating with uncaught exception of type NSException
How can I fix the error?