Reading NSUserDefaults in watchOS 2 (I know App Groups doesn't work)

Viewed 4365

Apple documentation says "Also, iOS automatically forwards a read-only copy of your iOS app’s preferences to Apple Watch. Your WatchKit extension can read those preferences using an NSUserDefaults object...". https://developer.apple.com/library/prerelease/watchos/documentation/General/Conceptual/WatchKitProgrammingGuide/SharingData.html#//apple_ref/doc/uid/TP40014969-CH29-SW1

But I can't read defaults in my WatchKit app that were saved in my iPhone app, am I doing something wrong?

In the WatchKit app, can I even save to (a WatchKit only) defaults, or does that not even work?

iPhone Data:

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(dataArray, forKey: "DataSaved"

Watch ExtensionDelegate:

let defaults = NSUserDefaults.standardUserDefaults()
print(defaults.arrayForKey("DataSaved"))
print(defaults.objectForKey("DataSaved"))

arrayForKey and objectForKey for print nil.

I must be doing something wrong, do you know what it would be?

4 Answers

Ns defaults.standard is particular to that target by using it you can access data within that target, in your case you need to access data in another target so listen you need to do two things one is 1. use app groups 2. don't use user defaults.standard use UserDefaults(suiteName:"group.yourgroup") to store and access the data refer this Link might be useful.

Related