Reputation: 3293
I'm trying to make a Today Extension, and in the main app favorite
is being correctly written and read from both ar
and ar2
. favorite
is a property of class Book
. However, when I try to access the favorite
property of an array of all Book
objects from the Today Extension, both ar
and ar2
are empty.
main app:
var favorite: Bool {
get {
let ar = NSUserDefaults.standardUserDefaults().stringArrayForKey("favorites") ?? []
let ar2 = NSUserDefaults(suiteName: "group.com.TodayExtension")
ar2?.synchronize()
let tempVar = ar2?.stringArrayForKey("favorites") ?? []
print("ar1: \(ar)")
print("tempVar: \(tempVar)")
return ar.contains {
$0 == slug
}
}
set {
var ar = NSUserDefaults.standardUserDefaults().stringArrayForKey("favorites") ?? []
let ar2 = NSUserDefaults(suiteName: "group.com.TodayExtension")
let contains = self.favorite
if (newValue && !contains) {
ar.append(self.slug)
ar2?.setObject(ar, forKey: "favorites")
ar2?.synchronize()
} else if (!newValue && contains) {
let idx = ar.indexOf {
$0 == slug
}
if let idx = idx {
ar.removeAtIndex(idx)
}
}
NSUserDefaults.standardUserDefaults().setObject(ar, forKey: "favorites");
}
}
Output:
ar1: ["Harry Potter", "Compound", "Nefarious"]
tempVar: ["Harry Potter", "Compound", "Nefarious"]
Today Extension:
func loadData(force: Bool, completion:(() -> Void)?) {
DATA.fetchEateries(force) { (error) -> (Void) in
dispatch_async(dispatch_get_main_queue(), {() -> Void in
if let completionBlock = completion {
completionBlock()
}
self.books = self.DATA.books
if self.books != [] {
for book in self.books {
if book.favorite {
print("I like it!")
} else {
print("I don't like \(book.name)")
}
}
}
else {
print("there are no books")
}
})
}
}
Output:
ar1: []
tempVar: []
I don't like Harry Potter
ar1: []
tempVar: []
I don't like Compound
ar1: []
tempVar: []
I don't like Nefarious
Upvotes: 2
Views: 511
Reputation: 17054
standardUserDefaults
doesn't return the same user defaults for both target. You must create app group and then use NSUserDefaults(suiteName: "group")
Upvotes: 1