如何让 CoreSpotlight 预测谁在打电话

How to make CoreSpotlight predict who is calling

我希望我的设备能够根据 Spotlight 人物指数预测谁在给我打电话。我已将人员信息上传到 Spotlight 索引,系统会在我搜索时提供信息,但在有人呼叫时不会提供信息。下面的代码做了所有这些事情,我不明白哪里出了问题

if people.count > 0 {
    var peopleArray = [CSSearchableItem]()
    var peopleGUIDs = [String]()
    for person in people {
        let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)

        // Basic AttributeSet setup
        attributeSet.title = person.nameForList
        attributeSet.contentDescription = person.division?.title

        // Add first phone number to AttributeSet
        var phoneNumber: NSString?
        let contacts = Array(person.contacts)
        for contact in contacts {
            if contact.type == "phone" {
                phoneNumber = contact.value as NSString
                break
            }
        }
        if phoneNumber != nil {
            if let preparedNumber = phoneNumber!.removingPercentEncoding {
                attributeSet.phoneNumbers = [preparedNumber]
                attributeSet.supportsPhoneCall = true
            }
        }

        attributeSet.displayName = person.name

        // Add photo number to AttributeSet
        if let photoPath = person.photo {
            let key = SDWebImageManager.shared().cacheKey(for: NSURL(string: photoPath) as URL!)
            let image = SDImageCache.shared().imageFromDiskCache(forKey: key)
            var data = Data()
            if let image = image {
                if let dataFromImage = UIImagePNGRepresentation(image) {
                    data = dataFromImage
                }
            } else {
                data = dataFromImage
            }
            attributeSet.thumbnailData = data
        }

        peoplesGUIDs.append(person.id)

        let item = CSSearchableItem(uniqueIdentifier: person.id, domainIdentifier: "com.it.companySpotlight", attributeSet: attributeSet)
        peopleArray.append(item)
    }

    CSSearchableIndex.default().indexSearchableItems(peopleArray) {  (error) in
        DispatchQueue.main.async(execute: {
            if let error =  error {
                print("Indexing error: \(error.localizedDescription)")
            } else {
                print("Search for people successfully indexed")
            }
        })
    }

}

有人知道如何解决这个问题吗?

过了一会儿,Paulw11说我需要使用CallKit扩展,于是有了解决方案:

  1. 向您的项目添加新目标"CallKIt extension"
  2. 创建应用程序组以向您的分机提供带有 phone 编号的文本文件,因为无法使用那里的数据库
  3. 确保您的联系人按数字升序排列以获得更好的性能
  4. 将联系人写入文件

    if #available(iOS 10.0, *) {
        let numbers = ["79175870629"]
    
        let labels = ["Stranger name"]
    
        // Replace it with your id
        let groupId = "group.YOUR.ID"
        let container = FileManager.default
            .containerURL(forSecurityApplicationGroupIdentifier: groupId)
        guard let fileUrl = FileManager.default
            .containerURL(forSecurityApplicationGroupIdentifier: groupId)?
            .appendingPathComponent("contacts") else { return }
    
        var string = ""
        for (number, label) in zip(numbers, labels) {
            string += "\(number),\(label)\n"
        }
    
        try? string.write(to: fileUrl, atomically: true, encoding: .utf8)
    
        CXCallDirectoryManager.sharedInstance.reloadExtension(
            withIdentifier: groupId)
    } else {
        // Fallback on earlier versions
    }
    
  5. 然后将 class LineReader 添加到您的分机 from this post
  6. 调用reloadExtension时会调用此方法

    override func beginRequest(with context: CXCallDirectoryExtensionContext) {
    context.delegate = self
    if #available(iOSApplicationExtension 11.0, *) {
        if context.isIncremental {
            addOrRemoveIncrementalBlockingPhoneNumbers(to: context)
            addOrRemoveIncrementalIdentificationPhoneNumbers(to: context)
        } else {
            addAllBlockingPhoneNumbers(to: context)
            addAllIdentificationPhoneNumbers(to: context)
        }
    } else {
        addAllBlockingPhoneNumbers(to: context)
        addAllIdentificationPhoneNumbers(to: context)
    }
    
    
    context.completeRequest()
    

    }

  7. 在我的例子中,我只实现了 addAllIdentificationPhoneNumbers 并从文件中读取联系人。您需要向默认生成的所有其他方法添加逻辑

    guard let fileUrl = FileManager.default
                .containerURL(forSecurityApplicationGroupIdentifier: "group.YOUR.ID")?
                .appendingPathComponent("contacts") else { return }
    
            guard let reader = CBLineReader(path: fileUrl.path) else { return }
            print("\(#function) \(fileUrl)")
            for line in reader {
                autoreleasepool {
                    let line = line.trimmingCharacters(in: .whitespacesAndNewlines)
    
                    var components = line.components(separatedBy: ",")
    
                    guard let phone = Int64(components[0]) else { return }
                    let name = components[1]
    
                    context.addIdentificationEntry(withNextSequentialPhoneNumber: phone, label: name)
                    print(#function + name)
                }
            }
    
  8. 转到设置 -> Phone -> 来电拦截和识别 -> 在您的应用

  9. 对面打开 swift
  10. 测试您的应用 :-) 希望它能对某人有所帮助