chaunv
chaunv

Reputation: 843

Swift: Reloading Content Blockers list in iOS 9

I'm try a new function in IOS 9: Content Blockers (Ad Blockers) In my app, I have 3 item (website) that I want block (ex: 1. abc.com 2. def.com 3. xyz.com) With every item, I use Switch control (ON/OFF) in order to user choose BLOCK or NOT BLOCK website.

When change status ON/OFF of switch then I want reload file blockerList.json. But I don't know how to do it.

Upvotes: 3

Views: 1085

Answers (1)

chaunv
chaunv

Reputation: 843

I found solution to solve my problem

Step 1: You need share data between "My App" and "Content Blocker Extension". (You create "App Groups" for "My App" and "Content Blocker Extension". Use NSUserDefault in order to save and share data).

Save data in "My App"

private let APP_GROUPS = "group.com.xxx"
let defaults: NSUserDefaults! = NSUserDefaults(suiteName: APP_GROUPS)
        if (SWITCH_1 is ON) {
                    idListBlocker = 1
                }
    if (SWITCH_2 is ON) {
                    idListBlocker = 2
                }
                defaults.setObject(idListBlocker, forKey: "idBlock")
                defaults.synchronize()

Step 2: When you change state of SWITCH ON/OFF in order to BLOCK/NOT BLOCK then you call function reload file list blocked content (blockerList.json)

if #available(iOS 9.0, *) {
            SFContentBlockerManager.reloadContentBlockerWithIdentifier("Your Bundle Identifier of Content Blocker Extension", completionHandler: nil)
        }

Step 3: In file ActionRequestHandler.swift, you load file list blocked content corresponding with option SWITCH that user choose

private let APP_GROUPS = "group.com.xxx"

    func beginRequestWithExtensionContext(context: NSExtensionContext) {
        let defaults = NSUserDefaults(suiteName: APP_GROUPS)
        let idBlock: Int? = defaults!.objectForKey("idBlock") as? Int
        if idBlock == 1 {
            let attachment = NSItemProvider(contentsOfURL: NSBundle.mainBundle().URLForResource("blockerList", withExtension: "json"))!

            let item = NSExtensionItem()
            item.attachments = [attachment]

            context.completeRequestReturningItems([item], completionHandler: nil);
        } else if idBlock == 2 {
            let attachment = NSItemProvider(contentsOfURL: NSBundle.mainBundle().URLForResource("blockerList_1", withExtension: "json"))!

            let item = NSExtensionItem()
            item.attachments = [attachment]

            context.completeRequestReturningItems([item], completionHandler: nil);
        }
    }

Corresponding with an option that user choose, you create a file list blocked content. Ex: My project I created 2 file blocked content: blockerList.json and blockerList_1.json.

It's my solution and work OK.

Upvotes: 3

Related Questions