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.
Asked
Active
Viewed 3,556 times
1 Answers
5
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
}
}
-
I wasn't having luck with NSUserDefaults. It resulted with the spinning wheel of infinity. I implemented App Groups - which might have been the problem. I'm only trying to store simple int variables...like I said, about 5 of them and I want the app to be completely native, without needing to fetch any data from the iPhone. – mackymoo Sep 24 '15 at 18:49
-
1You should use `initWithSuiteName:` and pass in the name of your app group. I'll update my answer. – Lance Sep 24 '15 at 18:51
-
Thank you. I'll try this tonight. :) – mackymoo Sep 24 '15 at 19:20
-
1This DOES NOT work on WatchOS2 anymore - http://stackoverflow.com/questions/30851729/nsuserdefaults-not-working-on-xcode-beta-with-watch-os2 – Sam B Dec 08 '15 at 23:46
-
@SamB This answer has nothing to do with sharing data between the watch and the phone. This is purely talking about storing data on the watch from within the watch app for later use. – Lance Dec 08 '15 at 23:49