HiKat
8/25/2015 - 7:44 AM

searchAPIsample.swift

searchAPIsample.swift

//
//  Datasource.swift
//  SearchAPIs
//
//  Created by Chris Grant on 18/06/2015.
//  Copyright © 2015 Scott Logic Ltd. All rights reserved.
//

import UIKit
import CoreSpotlight

class Datasource: NSObject {
    
    var people: [Person]
    
    override init () {
    
        let hisao = Person()
        hisao.name = "Hisao"
        hisao.id = "7"
        hisao.image = UIImage(named: "hisao")!
        hisao.privacy = "normal"
        
        let mrx = Person()
        mrx.name = "Mr.X"
        mrx.id = "7"
        mrx.image = UIImage(named: "mrx")!
        mrx.privacy = "private"
        
        people = [hisao, mrx]
    }
    
    func friendFromID(id: String) -> Person? {
        for person in people {
            if person.id == id {
                return person
            }
        }
        return nil
    }
    
    
    //=========Spotlightから検索可能にするためのアプリ側の対応==========
    func savePeopleToIndex() {
        
        var searchableItems = [CSSearchableItem]()
        
        //検索可能にするアイテムの登録
        for person in people {
            //=======プライバシー設定==========
            //personのprivacy属性を"private"にすればSpotlightの検索から除外される.(CSSearchableItemに登録されない.)
            if person.privacy == "private" {
                continue
            }
            //==============================
            let attributeSet = CSSearchableItemAttributeSet(itemContentType: "image" as String)
            attributeSet.title = person.name
            attributeSet.contentDescription = "This is an entry all about the interesting person called \(person.name)"
            attributeSet.thumbnailData = UIImagePNGRepresentation(person.image) // Doesn't work in beta 1. Known issue.

            let item = CSSearchableItem(uniqueIdentifier: person.id, domainIdentifier: "com.ios9daybyday.SearchAPIs.people", attributeSet: attributeSet)
            searchableItems.append(item)
        }
        
        CSSearchableIndex.defaultSearchableIndex().indexSearchableItems(searchableItems, completionHandler: { error -> Void in
            if error != nil {
                print(error?.localizedDescription)
            }
        })
    }
    //=============================================================
}