iOS NSCoreDataCoreSpotlightDelegate,如何为所有项目重新编制索引

时间:2019-04-22 12:29:22

标签: ios swift core-data corespotlight

我已经实现了NSCoreDataCoreSpotlightDelegate,但我错过了默认expirationDate为1个月的部分,现在我3个月前添加的项目没有出现在搜索索引中。

如何让NSCoreDataCoreSpotlightDelegate重新索引所有项目?

我曾经可以这样称呼:

let container = NSPersistentContainer(name: "MyApp")
let psd = NSPersistentStoreDescription(url:  FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.kiwlm.MyApp")!.appendingPathComponent("MyApp.sqlite"))

let mcdcsd = MyCoreDataCoreSpotlightDelegate(forStoreWith:psd, model: container.managedObjectModel)

container.persistentStoreDescriptions = [psd]

psd.setOption(mcdcsd, forKey:NSCoreDataCoreSpotlightExporter)

// uncomment the following to reindex all items
// mcdcsd.searchableIndex(CSSearchableIndex.default(), reindexAllSearchableItemsWithAcknowledgementHandler: {})

这是第一次,它将为所有项目重新编制索引,但是如果我重新运行上面一行未注释的应用程序,它将不会重新编制索引。

如果我卸载了该应用程序,请重新安装,然后取消注释上一行,然后它将再次为所有索引编制索引。

我如何重新为所有内容重新编制索引?

1 个答案:

答案 0 :(得分:1)

发生这种情况是因为NSCoreDataCoreSpotlightDelegate的实现使用beginIndexBatch和endIndexBatchWithClientState重新索引AllSearchableItems。因此,它正在保存索引状态。调用reindexAllSearchableItems时,Spotlight将检查状态并仅重新索引新项目。删除应用程序时,您还将删除索引状态。首次启动状态为空,NSCoreDataCoreSpotlightDelegate索引所有项目。

为了您的目的,我认为最好设置expirationDate而不是为所有项目重新编制索引。您可以在MyCoreDataCoreSpotlightDelegate上通过覆盖attributeSet来完成此操作:

override func attributeSet(for object: NSManagedObject) -> CSSearchableItemAttributeSet? {
    guard let attributeSet = super.attributeSet(for: object) else { return nil }
        if object.entity.name == "YourEntityName"  {
            // Setup necessary attributes
            attributeSet.setValue(Date.distantFuture, forKey: "expirationDate")
        }
    return attributeSet
}

要检查可搜索项的到期日期,可以使用CSSearchQuery:

class QueryExample {
    var query : CSSearchQuery? = nil
    func startQuery(withTitle title : String) {
        var allItems = [CSSearchableItem]()
        // All the items that start with the specified title property using case insensitive comparison
        let queryString = "title == \"*\(title)*\"c"
        let attributes = ["title", "displayName", "keywords",
                      "contentType"]
        self.query = CSSearchQuery(queryString : queryString,
                               attributes : attributes)
        self.query?.foundItemsHandler = { (items : [CSSearchableItem])
        -> Void in
            allItems.append(contentsOf: items)
        }
        self.query?.completionHandler = { (error ) -> Void in
            for item in allItems {
                print("expirationDate:\(item.expirationDate)")
            }
        }
        self.query?.start()
    }
}

像这样调用查询:

   override func viewDidLoad() {
       let query = QueryExample()
       query.startQuery(withTitle: "S")
   }

您应该在控制台上看到expirationDate:

  

到期日期:4001-01-01 00:00:00 +0000