Skip to content

Instantly share code, notes, and snippets.

@daehn
Last active April 23, 2019 03:05
Show Gist options
  • Save daehn/f01687f07fc74d382004 to your computer and use it in GitHub Desktop.
Save daehn/f01687f07fc74d382004 to your computer and use it in GitHub Desktop.
Swift protocols and protocol extensions to easily add and delete conforming instances to Spotlight. Blog post can be found here: http://silvandaehn.com/2015/09/25/Simplifying-CoreSpotlight/
import UIKit
import CoreSpotlight
import MobileCoreServices
public typealias Completion = NSError? -> Void
// MARK: - Searchable Protocol
public protocol Searchable {
static var spotlightDomainIdentifier: String { get }
var spotlightIdentifier: String { get }
var spotlightTitle: String { get }
var spotlightDescription: String? { get }
var spotlightImage: UIImage? { get }
var spotlightKeywords: [String]? { get }
}
public extension Searchable {
var spotlightImage: UIImage? { return nil }
var spotlightKeywords: [String]? { return nil }
var searchableItem: CSSearchableItem {
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = spotlightTitle
attributeSet.contentDescription = spotlightDescription
attributeSet.keywords = spotlightKeywords
let item = CSSearchableItem(
uniqueIdentifier: spotlightIdentifier,
domainIdentifier: self.dynamicType.spotlightDomainIdentifier,
attributeSet: attributeSet
)
item.expirationDate = .distantFuture()
item.attributeSet.thumbnailData = spotlightImage.flatMap(UIImagePNGRepresentation)
return item
}
func addToSpotlightIndex(
index: CSSearchableIndex = .defaultSearchableIndex(),
completion: Completion? = nil) {
index.indexSearchableItems([searchableItem], completionHandler: completion)
}
func removeFromSpotlightIndex(
index: CSSearchableIndex = .defaultSearchableIndex(),
completion: Completion? = nil) {
index.deleteSearchableItemsWithIdentifiers([spotlightIdentifier], completionHandler: completion)
}
static func deleteAllIndiciesFromSpotlightIndex(
index: CSSearchableIndex = .defaultSearchableIndex(),
completion: Completion? = nil) {
index.deleteSearchableItemsWithDomainIdentifiers([self.spotlightDomainIdentifier], completionHandler: completion)
}
}
extension SequenceType where Generator.Element == Searchable {
func addToSpotlightIndex(
index: CSSearchableIndex = .defaultSearchableIndex(),
completion: Completion? = nil) {
index.indexSearchableItems(self.map { $0.searchableItem }, completionHandler: completion)
}
func removeFromSpotlightIndex(
index: CSSearchableIndex = .defaultSearchableIndex(),
completion: Completion? = nil) {
index.deleteSearchableItemsWithIdentifiers(self.map { $0.spotlightIdentifier }, completionHandler: completion)
}
}
@skydivedan
Copy link

nice code! have you considered making it a Cocoapod?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment