Multiple filters for Safari content blocking Swift

折月煮酒 提交于 2019-12-03 14:35:48

I have been in same situation. Answer to this is bit tricky, so bear with me. You cannot write to file in bundle i.e blockerList.json is not writeable. Here is what you need to do,

  1. Enable App groups from TARGETS->YOUR MAIN APP -> Capabilities -> App Groups. And add unique identifier for app groups. Do same with extension. (Use same identifier as group name which you entered for main app)
  2. Create a file in Container directory.
  3. Write rules (json) to that file.
  4. Reload extension once you have written rules.
  5. Read rules from Container directory in content blocker extension.

From your main app create file and write json rules into that file as:

let jsonData = try! JSONSerialization.data(withJSONObject: webFilters, options: JSONSerialization.WritingOptions.prettyPrinted)

//Convert back to string. Usually only do this for debugging

if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {

                        let file = "conbo.json"


                        if let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "YOUR_GROUP_IDENTIFIER") {

                            let path     = dir.appendingPathComponent(file)

                            do {

                                try JSONString.write(to: path, atomically: false, encoding: String.Encoding.utf8)

                                let id = "YOUR_CONTENT_BLOCKER_BUNDLE_IDENTIFIER"
                                SFContentBlockerManager.reloadContentBlocker(withIdentifier: id) {error in



                                    guard error == nil else {
                                        print(error ?? "Error")
                                        return
                                    }

                                    print("Reloaded")
                                }

                            }
                            catch {
                            }
                        }


                    }

Now in extension read file from container as:

class ContentBlockerRequestHandler: NSObject, NSExtensionRequestHandling {

func beginRequest(with context: NSExtensionContext) {

    let file = "conbo.json"


    if let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "YOUR_APP_GROUP_IDENTIFIER") {

        let path     = dir.appendingPathComponent(file)

        do {



            do {
                let attachment =  NSItemProvider(contentsOf: path)!

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

                context.completeRequest(returningItems: [item], completionHandler: nil)


            } 



        }

    }



}



}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!