数据持久 WatchOS 4.0

Data Persistent WatchOS 4.0

我在现有的 IOS 应用程序中制作了 watchApp 我已经成功地将数据从 IOS 传递到 WatchOS 并通过委托方法在 watch OS 中接收数据,如下面的代码所示。

我的问题是数据在 WatchOS 中不持久。每当我需要使用 watchApp 时,我都必须先打开 IOS 应用程序,然后它会更新 watchApp。

我尝试了 AppGroups,但它似乎不再适用于 watchOS 2.0+。

那么我怎样才能将数据保存在手表OS上并且只通过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))
    }

UserDefaults 从 watchOS 2 开始可用(用于存储设置等轻量级数据)。核心数据也可用。