I was in the same situation. The answer to this is a bit complicated, so bear with me. You can not write to a file in the kit ie blockerList.jsonnot written. Here is what you need to do
- Enable application groups from
TARGETS→ YOUR MAIN APP→ Capabilities→ App Groups. And add a unique identifier for application groups. Do the same with the extension. (Use the same identifier as the group name that you entered for the main application) - Create a file in the container directory.
- Write the rules (json) to this file.
- Restart the extension once you have written the rules.
- Reading rules from the Container directory in the content block extension.
From the main application, create a file and write json rules in this 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 the extension read the file from the 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)
}
}
}
}
}