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.
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.
@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
private var _appGroupDefaults = NSUserDefaults(suiteName: "com.whatever.yourappgroupname")!
extension NSUserDefaults {
public func appGroupDefaults() -> NSUserDefaults {
return _appGroupDefaults
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With