Watch OS 2 - How store data on Watch for fully native app?

可紊 提交于 2019-12-08 18:05:00

问题


I need to store about 5 variables on the WatchKit Extension - Watch side Only. The app is going to be completely native, without passing any info to the iPhone. I need the data to persist if the watch is re-booted. The app currently resets to the default variable states upon reboot. I'm not sure what to use. I found information online about using the watch keychain for storing key-value data pairs (username/password), but I don't think that's what I should use here. Appreciate some help.


回答1:


watchOS 2 has access to CoreData, NSCoding and NSUserDefaults. Depends on the data you want to store but those are the best (first party) options.

If you are going to use NSUserDefaults, do not use standardUserDefaults you should use initWithSuiteName: and pass in the name of your app group.

You could even make a category/extension on NSUserDefaults to make this easier.

Objective-C

@interface NSUserDefaults (AppGroup)
+ (instancetype)appGroupDefaults;
@end

@implementation NSUserDefaults (AppGroup)

+ (instancetype)appGroupDefaults {
    static NSUserDefaults *appGroupDefaults = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        appGroupDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"com.whatever.yourappgroupname"];
    });
    return appGroupDefaults;
}

@end

Swift

private var _appGroupDefaults = NSUserDefaults(suiteName: "com.whatever.yourappgroupname")!

extension NSUserDefaults {
    public func appGroupDefaults() -> NSUserDefaults {
        return _appGroupDefaults
    }
}


来源:https://stackoverflow.com/questions/32768412/watch-os-2-how-store-data-on-watch-for-fully-native-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!