Safari内容拦截的多个过滤器Swift [英] Multiple filters for Safari content blocking Swift
问题描述
我正在构建一个简单的内容阻止应用程序.
它有效,但是我想用UISwitches
(保存到NSUserDefaults
)应用过滤器(要阻止的站点和不阻止的站点).
由于内容阻止扩展程序使用json,因此我不清楚如何选择多个json文件以同时运行.
I'm building a simple content-blockin app.
It works, but i want to apply filters (which webs to block and which not) with UISwitches
(saved to NSUserDefaults
).
Because the content blocking extension uses json it's unclear to me how can i select multiple json files to function simultaneously.
任何想法如何实现?多个扩展?以某种方式组合和拆分json文件?
Any ideas how it can be achieved? Multiple extensions? Combining and splitting json files somehow?
推荐答案
我遇到过同样的情况.回答这个问题有些棘手,所以请耐心等待.您无法写入文件包中的文件,即blockerList.json
是不可写的.这是您需要做的,
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,
- 启用
TARGETS
->YOUR MAIN APP
->Capabilities
->App Groups
中的应用程序组.并为应用程序组添加唯一标识符.对扩展名也一样. (使用与您在主应用中输入的组名相同的标识符) - 在Container目录中创建一个文件.
- 将规则(json)写入该文件.
- 编写规则后重新加载扩展名.
- 从内容阻止程序扩展中的Container目录中读取规则.
- 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) - Create a file in Container directory.
- Write rules (json) to that file.
- Reload extension once you have written rules.
- Read rules from Container directory in content blocker extension.
在主应用程序中创建文件,并将json规则写入该文件,如下所示:
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)
}
}
}
}
}
这篇关于Safari内容拦截的多个过滤器Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!