iOS内容阻止扩展加载多个JSON文件

时间:2015-09-15 04:59:24

标签: ios swift safari-content-blocker

是否可以从内容拦截器扩展程序返回多个JSON文件?在我的UI用户中启用/禁用不同的过滤器,每个过滤器由单独的文件表示。我目前有(尽管迭代多次,它只加载一个):

func beginRequestWithExtensionContext(context: NSExtensionContext) {
    var items = Array <NSExtensionItem>()

    let resources = ["a", "b", "c"]
    for resource in resources {
        let url = NSBundle.mainBundle().URLForResource(resource, withExtension: "json")

        if let attachment = NSItemProvider(contentsOfURL: url) {
            let item = NSExtensionItem()
            item.attachments = [attachment]
            items.append(item)
        }
    }
    context.completeRequestReturningItems(items, completionHandler: nil)
}

我尝试过多件商品和一件带有多个附件的商品。如果不可能有单独的文件,任何方式组合多个(或以编程方式生成)?

3 个答案:

答案 0 :(得分:3)

可以有多个JSON文件并将其用于Content Blocker扩展。

1)将多个扩展项传递给completeRequestReturningItems方法时抛出SFContentBlockerErrorDomain

2)无法将多个附件附加到NSExtension,对源代码的评论说,附件并不是一组备用数据格式/类型,而是一个集合包含在社交媒体帖子中。这些项始终是键入的NSItemProvider。我估计你不能添加多个json数据作为附件,因为它们不是一系列用于创建消息的附件。

我的解决方案(已验证可行):

可以使用item(NSData)和typeIdentifier初始化NSItemProvider。

let aData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("a", withExtension: "json")!)
let bData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("b", withExtension: "json")!)

aJSON = `convert aData to JSON`
bJSON = `convert bData to JSON`
combinedJSON = `aJSON + bJSON`
combinedData = 'convert combinedJSON to NSData'

let attachment = NSItemProvider(item: combinedData, typeIdentifier: kUTTypeJSON as String)

现在,您可以根据您的偏好创建带附件的组合数据。

答案 1 :(得分:3)

对于那些好奇的我最终添加代码来动态生成JSON文件(持久化到磁盘)。从其他答案来看,似乎可以通过返回文件的NSData表示来避免保存步骤 - 尽管该尝试对我来说失败了。这是我的片段:

import UIKit
import MobileCoreServices

class ActionRequestHandler: NSObject, NSExtensionRequestHandling {

    func beginRequestWithExtensionContext(context: NSExtensionContext) {
        let item = NSExtensionItem()
        let items = [item]

        let url = buildJSONFileURL()
        if let attachment = NSItemProvider(contentsOfURL: url) { item.attachments = [attachment] }

        context.completeRequestReturningItems(items, completionHandler: nil)
    }

    func buildJSONFileURL() -> NSURL {
        let directories = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let directory = directories[0]

        let path = directory.stringByAppendingFormat("/block.json")

        let selector = [...] // Dynamically Generated
        let dictionary = [[
            "action": [ "type": "css-display-none", "selector": selector ],
            "trigger": [ "url-filter": ".*" ]
            ]]

        let data = try! NSJSONSerialization.dataWithJSONObject(dictionary, options: NSJSONWritingOptions.PrettyPrinted)
        let text = NSString(data: data, encoding: NSASCIIStringEncoding)!

        try! text.writeToFile(path, atomically: true, encoding: NSASCIIStringEncoding)

        return NSURL(fileURLWithPath: path)
    }

}

答案 2 :(得分:1)

您可以将两个JSON规则文件合并为一个文件,然后使用该文件。

    import UIKit
    import MobileCoreServices
    class ContentBlockerRequestHandler: NSObject, NSExtensionRequestHandling {

        func beginRequest(with context: NSExtensionContext) {

        let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "you app group identifier")

                let sourceURLRules = sharedContainerURL?.appendingPathComponent("Rules1.json")
                let sourceURLRules2 = sharedContainerURL?.appendingPathComponent("Rules2.json")
                do {
                    let jsonDecoder = JSONDecoder()

                    let dataFormRules1 = try Data(contentsOf: sourceURLRules1!, options: .mappedIfSafe)// Rule is Decode able Swift class            
                   let  rulesArray1 = try? jsonDecoder.decode(Array<Rule>.self,from: dataFormRules1)

                    let dataFormRules2 = try Data(contentsOf: sourceURLRules2!, options: .mappedIfSafe)
                    let  rulesArray2 = try? jsonDecoder.decode(Array<Rule>.self,from: dataFormRules2)

                    saveCombinedRuleFile(ruleList: rulesArray1! + rulesArray2!)

                } catch {
                    //handle error condition
                }

                let sourceURLCombinedRule = sharedContainerURL?.appendingPathComponent("CombinedRule.json")
                let combinedRuleAttachment = NSItemProvider(contentsOf: sourceURLCombinedRule)
                let item = NSExtensionItem()
                item.attachments = [combinedRuleAttachment]
                context.completeRequest(returningItems: [item], completionHandler: nil)
            }

            func saveCombinedRuleFile(ruleList:[Rule]) {
                let encoder = JSONEncoder()
                if let encoded = try? encoder.encode(ruleList) {
                    let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "you app group identifier")
                    if let json = String(data: encoded, encoding: .utf8) {
                        print(json)
                    }
                    if let destinationURL = sharedContainerURL?.appendingPathComponent("CombinedRule.json") {
                        do {
                            try  encoded.write(to: destinationURL)
                        } catch {
                            print ("catchtry")
                        }
                    }
                }
            }
        }