我正在尝试使用包含在嵌入式框架中的通用模块在我的 iOS 和 WatchKit 扩展之间共享数据。公共模块类与应用组共享保存在 NSUserDefault 中的数据。
但是,从 WatchKit 扩展读取时,看不到我在 iOS 应用程序中写入应用程序组共享的内容。
我在两个目标中启用了具有相同组 ID 的应用组。iOS 读取和写入没有错误,如果 Watch 写入数据,它也会正确读取数据——但两者都看不到对方的写入。
任何想法如何解决非常感谢。
public class ShareManager() {
private let sharedKey = “kungFuShare"
public var kungfuFighters:Array<KungFu> = [];
public init() {
readFromShare()
}
public func readFromShare() {
let myData = NSUserDefaults(suiteName: "group.com.27feathers.kungfu"
if let rawData: NSData = myData?.objectForKey(sharedKey) as? NSData
{
var myData: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(rawData);
self.kungfuFighters = myData as? [KungFu] ?? []
}
}
public func writeToShare() {
let myData = NSUserDefaults(suiteName: "group.com.27feathers.kungfu")
let saveData = NSKeyedArchiver.archivedDataWithRootObject(self.kungfuFighters)
myData?.setObject(saveData, forKey: sharedKey)
myData?.synchronize() // same behavior with or without this
}
}
public class KungFu: NSObject, NSCoding {
public var fighterName:String
public init(fighterName:String) {
self.fighterName = fighterName
}
required public init(coder: NSCoder) {
self.fighterName = coder.decodeObjectForKey("fighterName")! as String
super.init()
}
public func encodeWithCoder(coder: NSCoder) {
coder.encodeObject(self.fighterName, forKey: "fighterName")
}
}