Watch OS 2 - How to store data on Watch for a completely native application?

I need to save about 5 variables on WatchKit Extension - only Watch Watch. The application will be completely native, without transferring information to the iPhone. I need the data to be saved if the clock is reset. The application restarts to the default state of the variable upon reboot. I am not sure what to use. I found information on the Internet on how to use a keychain to store data pairs with a key (username / password), but I don’t think that what I should use here. Appreciate some help.

+6
source share
1 answer

WatchOS 2 has access to CoreData, NSCoding, and NSUserDefaults. Depends on the data you want to save, but these are the best (first) options.

If you intend to use NSUserDefaults, do not use standardUserDefaults , you should use initWithSuiteName: and pass the name of your application group.

You can even make a category / extension for NSUserDefaults to make it 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 } } 
+5
source

All Articles