Deleting Your App’s Searchable content - Web and Search - iOS 9 Swift Programming Cookbook (2015)

iOS 9 Swift Programming Cookbook (2015)

Chapter 6. Web and Search

6.3 Deleting Your App’s Searchable content

Problem

You have indexed some items in Spotlight and you would like to get rid of that now.

Solution

Use a combination of the following methods on CSSearchableIndex:

§ deleteAllSearchableItemsWithCompletionHandler(_:)

§ deleteSearchableItemsWithDomainIdentifiers(_:completionHandler:)

§ deleteSearchableItemsWithIdentifiers(_:completionHandler:)

Discussion

Let’s have a look at an example. Say that you have already indexed some items (see Recipe 6.1) and you want to delete that content. The first thing is to get a handle to the CSSearchableIndex class:

let identifiers = [

"com.yourcompany.etc1",

"com.yourcompany.etc2",

"com.yourcompany.etc3"

]

let i = CSSearchableIndex(name: NSBundle.mainBundle().bundleIdentifier!)

Then use the fetchLastClientStateWithCompletionHandler(_:) method on the index to get the latest application state that you had submitted to the index. After that, you can begin deleting the items inside the identifiers array by using the beginIndexBatch() function on our index. Then use the deleteSearchableItemsWithIdentifiers(_:) function, which returns a completion handler. This handler will return an optional error that dictates whether the deletion went OK or not. Once we are done, we end the batch updates on the index with theendIndexBatchWithClientState(_:completionHandler:) method:

i.fetchLastClientStateWithCompletionHandler {clientState, err in

guard err == nil else{

print("Could not fetch last client state")

return

}

let state: NSData

if let s = clientState{

state = s

} else {

state = NSData()

}

i.beginIndexBatch()

i.deleteSearchableItemsWithIdentifiers(identifiers) {err in

if let e = err{

print("Error happened \(e)")

} else {

print("Successfully deleted the given identifiers")

}

}

i.endIndexBatchWithClientState(state, completionHandler: {err in

guard err == nil else{

print("Error happened in ending batch updates = \(err!)")

return

}

print("Successfully batch updated the index")

})

}

NOTE

The content identifiers that I’ve put in the identifiers array are just an example. I don’t know what identifiers you want to use, but make sure that you udpate this array before attempting to delete the existing indexed items.

See Also