更新Safari App Extension内容阻止程序列表

时间:2019-03-01 05:26:34

标签: safari safari-app-extension safari-content-blocker

从Safari应用程序扩展创建本地内容阻止程序时,如何在插件加载后更新静态JSON列表?

我现在唯一看到的方法是部署该应用程序的全新版本,该版本不会为用户自动更新。

是否可以从另一个URL更新内容阻止程序的JSON阻止列表文件,而不必通过Apple商店更新Safari应用程序扩展?

1 个答案:

答案 0 :(得分:0)

,您有可能可以更新JSON阻止列表

第1步:

为内容阻止规则创建新的JSON

第2步: 将JSON文件保存在共享容器中

fileprivate func saveRuleFile(ruleList:[Rule]) {
        let encoder = JSONEncoder()
        if let encoded = try? encoder.encode(ruleList) {

            let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xxx.xxxx.xxx")
            print("sharedContainerURL = \(String(describing: sharedContainerURL))")

            if let json = String(data: encoded, encoding: .utf8) {
                print(json)
            }

            if let destinationURL = sharedContainerURL?.appendingPathComponent("Rules.json") {
                do {
                    try  encoded.write(to: destinationURL)
                } catch {
                    print (error)
                }
            }
        }
    }

步骤3:调用此方法,要求内容阻止程序重新加载规则

SFContentBlockerManager.reloadContentBlocker(withIdentifier:"com.xxxx.xxx.xxxx", completionHandler: nil)

步骤:4 从共享容器中读取JSON规则文件,并将规则传递给内容阻止程序扩展

func beginRequest(with context: NSExtensionContext) {
        let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.xxx.xxx.xxx")
        let sourceURL = sharedContainerURL?.appendingPathComponent("Rules.json")
        let ruleAttachment = NSItemProvider(contentsOf: sourceURL)
        let item = NSExtensionItem()
        item.attachments = ([ruleAttachment] as! [NSItemProvider])
        context.completeRequest(returningItems: [item], completionHandler: nil)
    }