1

我在我的项目 safari 内容拦截器扩展中使用。当我在 blockerList.json 文件中静态设置规则并运行项目时,一切正常。现在我想使用下面描述的技术动态设置我的规则。

伙计们请帮我在运行时动态设置规则。

我试试这个,但是当我遇到错误时

  1. 从视图控制器类加载
fileprivate func saveRuleFile() {

        let ruleList = [["trigger":["url-filter": ".*"],"action":["type": "block"]]]

        let encoder = JSONEncoder()
        encoder.outputFormatting = .prettyPrinted
        if let encoded = try? encoder.encode(ruleList) {

            let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.****.***")
            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)
                }
            }
        }
    }
  1. 并在 ContentBlockerRequestHandler 类中编写
func beginRequest(with context: NSExtensionContext) {
 let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.****.***")
        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)
    }
  1. 我尝试使用加载
SFContentBlockerManager.reloadContentBlocker(withIdentifier: "com.app.*****", completionHandler: {(error) in
            if error != nil{
                print("error: \(error.debugDescription)")
            }
        })

当尝试在运行时执行第三个数字块时,我遇到了错误。但是我转到文件路径并检查了 json 绝对没问题,它是一个有效的 json。

Error Domain=WKErrorDomain Code=2 "(null)" UserInfo={NSHelpAnchor=Rule list compilation failed: Failed to parse the JSON String.}
4

1 回答 1

0

尝试使用 JSONSerialization。它对我很有用:)

fileprivate func saveRuleFile() {

    let ruleList = [["trigger":["url-filter": ".*"],"action":["type": "block"]]]

    let jsonAsData = try! JSONSerialization.data(withJSONObject: ruleList)

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

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

}
于 2020-05-11T09:26:02.313 回答