Search code examples
objective-cios9safari-extensionadblock

can't load Safari contentBlocker. because can't access app group's NSUserDefault


I am making iOS 9 Safari AdBlocker app. I am using the module of AdBlockPlusSafari. App works good on simulator.

But when try to run it on device(iPhone6), it fails to reload contentBlocker.

[SFContentBlockerManager 
 reloadContentBlockerWithIdentifier:self.contentBlockerIdentifier 
 completionHandler:^(NSError *error) {
    if (error) {
        NSLog(@"Error in reloadContentBlocker: %@", error);
    }

    dispatch_async(dispatch_get_main_queue(), ^{
        wSelf.reloading = NO;
        [wSelf checkActivatedFlag];
        if (completion) {
            completion(error);
        }
    });
}];

it gives error Error Domain=ContentBlockerErrorDomain Code=3 "(null)"

It caused by accessing the values in NSUserDefault (App Group).

- (instancetype)init
{
    if (self = [super init])
    {
        _bundleName = [[[[[NSBundle mainBundle] bundleIdentifier] componentsSeparatedByString:@"."] subarrayWithRange:NSMakeRange(0, 2)] componentsJoinedByString:@"."];
        NSString *group = [NSString stringWithFormat:@"group.%@.%@", _bundleName, @"AdBlockerPro"];

        NSLog(@"Group name: %@", group);
        _adblockProDetails = [[NSUserDefaults alloc] initWithSuiteName:group];
        [_adblockProDetails registerDefaults:
     @{ AdblockProActivated: @NO,
        AdblockProEnabled: @YES
        }]; 

        _enabled = [_adblockProDetails boolForKey:AdblockProEnabled];
        _activated = [_adblockProDetails boolForKey:AdblockProActivated];
    }
    return self;
}

The App Group name in host app and safari extension is same. But in Safari extension, when app accesses the setting in NSUserDefault, it gives me the error. In Project setting/Capabilities, I did all for App Group. In app id, it involves app group name exactly. This happens on only device. On simulator, it works good. I can't find the reason of this error.

Please help me if you are experienced this. Looking forward to your help.


Solution

  • I found the reason myself. I have put something (NSMutableDictionary) in app group container and did something to write file to extension bundle. It is prohibited by Apple.

    So I deleted all from AdBlockManager (interacts with app group) except flag variables (Boolean type). And I proceeded the file management using NSFileManager.

    http://www.atomicbird.com/blog/sharing-with-app-extensions

    Finally, app extension is working for me on device.

    Good luck!