0

I have a small application that is sharing data between an the app and a today extension. I have a group set up for the app and extension, and data is correctly being passed to the extension through NSUserDefaults. I have verified that the data is being correctly sent to the extension. I have also verified that the extension is correctly changing the data in the defaults. The problem that I am having is that the app is not picking up the change in the defaults. If I shut down the app and restart it, the changes are there, but the changes are not visible when returning to the app. Basically, the app is not picking up on changes made to the defaults.

My code looks like this:

override func viewDidLoad() {
    super.viewDidLoad()

    textField.delegate = self

    let defaults = NSUserDefaults.init(suiteName: "group.SDK.TodayWidgetTest")
    defaults?.addObserver(self, forKeyPath: "testing", options: NSKeyValueObservingOptions.New, context: nil)

    defaults?.synchronize()
}

I added the following event:

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
    print("Test")
}

If I set the testing key in the app, observeValueForKeyPath fires. If I make a change to the default data in the extension, this event never fires. Here is the code that I have in the extension.

@IBAction func setValue(sender: UIButton) {
    let defaults = NSUserDefaults.init(suiteName: "group.SDK.TodayWidgetTest")

    defaults!.setValue("Testing", forKeyPath: "testing")
}

All this code does is set the testing key to a value of Testing. When I update the data on the extension, the event in the app is not firing.

How can I set the code up so that it will catch any time that the testing key is changed?

zisoft
  • 22,770
  • 10
  • 62
  • 73
Scott Kilbourn
  • 1,545
  • 6
  • 18
  • 40
  • http://stackoverflow.com/questions/28284989/nsuserdefaultsdidchangenotification-and-today-extensions – Gruntcakes Jan 01 '17 at 17:23
  • This post deals with updating the extension from some action on the container app. My issue is opposite that. I need to tell the container to update whenever an action is taken on the extension. – Scott Kilbourn Jan 01 '17 at 17:45
  • But that also says the root cause is the app and the extension run in different processes. How is that same root cause not applicable in your case? – Gruntcakes Jan 01 '17 at 18:12
  • Thank you. This was a great suggestion that works perfectly. – Scott Kilbourn Jan 01 '17 at 21:20

0 Answers0