首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >数据持久化WatchOS 4.0

数据持久化WatchOS 4.0
EN

Stack Overflow用户
提问于 2019-07-04 16:42:09
回答 1查看 125关注 0票数 0

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

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

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

那么,如何将数据保存在watchOS上并仅通过updateApplicationContextWithApplicationContext更新呢?

代码语言:javascript
复制
    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中的数据:

代码语言:javascript
复制
func session(_ session: WCSession, didReceiveApplicationContext applicationContext: [String : Any])
    {
        print(" \(applicationContext)")
        self.delegate?.dataFromIOS(DataSource(data: applicationContext))
    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-05 01:56:26

UserDefaults可在watchOS 2中使用(用于存储轻量级数据,如设置)。还提供了核心数据。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56891829

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档