Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSUserDefaults(suiteName:) on iOS 9 and WatchOS 2 - not working?

I've done this before but nothing seems to be working. Here's my code:

Saving in the iOS App

let groupDefaults = NSUserDefaults(suiteName: "group.company.appSharedDefaults")
groupDefaults?.setObject(theArray, forKey: "theKey")
groupDefaults?.synchronize()

Reading (works on iOS but not WatchOS 2)

let groupDefaults = NSUserDefaults(suiteName: "group.company.appSharedDefaults")

if groupDefaults!.objectForKey("theKey") != nil {
    textEmojiArray = NSMutableArray(array: groupDefaults!.objectForKey("theKey") as! NSArray)
} else {        
    //error
}

Both .entitlements files contain group.company.appSharedDefaults

App Groups capability have been turned on and appropriate group checked off on both targets.

Right now when I run the read code on the watch objectForKey returns nil but it works on iOS (device and simulator results are the same).

What am I missing!?

like image 974
JustAnotherCoder Avatar asked Sep 03 '15 04:09

JustAnotherCoder


1 Answers

In watchOS 2 you need to keep in mind that there is 2 different processes running:

  1. Apple Watch Process
  2. iPhone Process

Both of these processes have their own sandbox that's why they call it "native", so if you try to use the shared NSUserDefaults it will not work because the Apple watch app has a completely different sandbox than the host iPhone app.

If you want to save something from your phone to the NSUserDefaults on the Apple watch Target:

Use WatchConnectivity to send the data you want to save to the watch. Then when the watch receives the data you sent to it, save it to the Apple watch's default NSUserDefaults.

like image 57
Suneet Tipirneni Avatar answered Nov 03 '22 14:11

Suneet Tipirneni