0

My Today Extensions works perfectly on beta 4, and I have implement a simple cache when Today Extensions first loaded.

let defaults = NSUserDefaults(suiteName: "group.ReadWidget") // app group 
var feed = [String: String]()

override func viewDidLoad() {
    getCache()

    // The feed is empty
}

func parseRSS() {
    ...
    // Parse in background

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
          self.parser = NSXMLParser(contentsOfURL:NSURL(string:url))
          self.parser.delegate = self
          self.parser.parse() // populate the feed
          self.saveCache()    // Save the feed
          ...
        })
    })
}

func saveCache() {
    defaults.setObject(feed, forKey:"feed")
    defaults.synchronize()
}

func getCache() {
    if defaults.objectForKey("feed") {
        feed = defaults.dictionaryForKey("feed") as [String : String]
    }
    else {
        feed = [:]
    }
}

In beta 5, after saveCache(), and when getCache() back in Today Extension reloaded, I always got back an empty dictionary.

I am using NSUserDefaults(suiteName:...) to store cache. I have also tried NSUserDefaults.standardUserDefaults() and the result is the same.

btw, which NSUserDefaults is the preferred method for loading and saving cache? The cache is not shared with the main app.

Andrew
  • 15,357
  • 6
  • 66
  • 101
Lim Thye Chean
  • 8,704
  • 9
  • 49
  • 88

1 Answers1

0

This works:

var defaults = NSUserDefaults.standardUserDefaults()
var feed = [String:String]()

func getCache() {
    if defaults.objectForKey("feed") {
        feed = defaults.dictionaryForKey("feed") as [String : String]
    }
    else {
        feed = [:]
    }
    println("feed: \(feed)")
}
zaph
  • 111,848
  • 21
  • 189
  • 228
  • The feed is a global variable. Both getCache and saveCache uses it. Is something being clear away? – Lim Thye Chean Aug 05 '14 at 02:48
  • Is there any difference? – Lim Thye Chean Aug 05 '14 at 03:17
  • Not really but you have not provided a self-contained **minimal** test so there is no way to know. – zaph Aug 05 '14 at 03:36
  • From a testability (and design) POV it is best to pass values into and return them than using globals such as `feed`. In the current question code is is not shown where `feed` is set prior to `saveCache()`. – zaph Aug 05 '14 at 03:41
  • feed is set in self.parser.parse() as this is a RSS parser. It is OK as it is very difficult to condense all these into a minimal test, but thanks for your help. The code works prior to beta 5. – Lim Thye Chean Aug 05 '14 at 04:11