Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 286
mackymoo Avatar asked Sep 24 '15 18:09

mackymoo


1 Answers

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
    }
}
like image 79
Lance Avatar answered Sep 27 '22 18:09

Lance