4

I have a really strange problem while developing a content blocker extension. I'm trying to share data between it and my app using NSUserDefaults with an app group but but reading something from the app group always crashes the extension.

Here is a sample code that is working:

func beginRequestWithExtensionContext(context: NSExtensionContext) {
    NSUserDefaults(suiteName: "group.Bug")!.setBool(true, forKey: "here")
    NSUserDefaults(suiteName: "group.Bug")!.synchronize()

    let attachment = NSItemProvider(contentsOfURL: NSBundle.mainBundle().URLForResource("blockerList", withExtension: "json"))!
    let item = NSExtensionItem()
    item.attachments = [attachment]
    context.completeRequestReturningItems([item], completionHandler: nil);
}

The extension doesn't return an error and I can then read here in my app.

Here is the same thing with one more line trying to read the value I just settled:

func beginRequestWithExtensionContext(context: NSExtensionContext) {
    NSUserDefaults(suiteName: "group.Bug")!.setBool(true, forKey: "here")
    NSUserDefaults(suiteName: "group.Bug")!.synchronize()
    NSLog("%@", (NSUserDefaults(suiteName: "group.Bug")!.boolForKey("here")))

    let attachment = NSItemProvider(contentsOfURL: NSBundle.mainBundle().URLForResource("blockerList", withExtension: "json"))!
    let item = NSExtensionItem()
    item.attachments = [attachment]
    context.completeRequestReturningItems([item], completionHandler: nil);
}

It returns Optional(Error Domain=ContentBlockerErrorDomain Code=3 "(null)").

The problem only happens when running the code on a real device, it's working on the simulator. Does someone know what could be the source of the problem?

Armand Grillet
  • 3,229
  • 5
  • 30
  • 60
  • Hi, I have the same problem, were you able to find the source of the issue? – Peter Robert Oct 06 '15 at 07:02
  • Hi, have the same issue. Did you solve this? – bartl Oct 12 '15 at 14:03
  • 1
    I've spoken with the developers working on the Content Blocker API and we haven't been able to find the source of the bug. If you can find what is going wrong on the system (e.g. a better error message than the one in the question), please leave a comment and fill a bug report to Apple. – Armand Grillet Oct 17 '15 at 09:34

2 Answers2

-1

When writing data to NSUserDefaults, don't forget NSUserDefaults( ).synchronize()

Daniel Krom
  • 9,751
  • 3
  • 43
  • 44
highsun16
  • 301
  • 3
  • 12
-1

Don't read the value back immediately after writing to user defaults because first of all the value is known in code and second of all the process to synchronize the database works asynchronously.

That means reading the value back at once is unreliable.

vadian
  • 274,689
  • 30
  • 353
  • 361