我已经在现有的IOS应用中制作了一个watchApp 我已成功将数据从IOS传递到WatchOS,并通过委托方法在watch OS中接收数据,如下面的代码所示。
我的问题是WatchOS中的数据不是持久的。每当我需要使用watchApp时,我必须先打开IOS应用程序,然后再更新watchApp。
我尝试了AppGroups,但似乎在watchOS 2.0+上不再起作用了。
那么我如何才能将数据保存在watchOS上并仅通过updateApplicationContextWithApplicationContext
进行更新?
NSMutableDictionary * cardDataForWatch = [[NSMutableDictionary alloc] init];
for (Card * card in self.cards)
{
NSMutableDictionary<NSString *, id> *storedData = [[NSMutableDictionary alloc] init];
Store * store = [StoreHelper getStoreForCard:card];
NSString * color = [ColorHelper hexStringForColor:[[store getColorPalette] getHighlightColor]];
NSString * barcode = [card barcode];
if (color != nil)
{
[storedData setValue:color forKey:@"color"];
}
if (barcode != nil)
{
[storedData setValue:barcode forKey:@"barcode"];
}
UIImageView * imageView = [[UIImageView alloc] init];
imageView.frame = CGRectMake(0, 0, 100, 90);
[BarcodeRenderer renderBarcode:card to:imageView andLabel:nil];
NSData * barcodeImage = UIImagePNGRepresentation([imageView image]);
[storedData setValue:barcodeImage forKey:@"barcodeImage"];
[cardDataForWatch setValue:storedData forKey:[card store]];
}
@try {
[[WatchSessionManager sharedManager] updateApplicationContextWithApplicationContext:cardDataForWatch error:nil];
然后我通过委托方法在watchOS中接收数据:
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any])
{
print("? \(applicationContext)")
self.delegate?.dataFromIOS(DataSource(data: applicationContext))
}
答案 0 :(得分:1)
UserDefaults自watchOS 2起可用(用于存储诸如设置之类的轻量数据)。核心数据也可用。