Я делаю приложение, подобное TrueCaller.Сначала я могу заблокировать номер, но всякий раз, когда я обновляю / добавляю больше номера, мне нужно вручную отключить и включить плагин каталога вызовов в Настройки -> Телефон -> Блокировка и идентификация вызовов , чтобы обновить список,Я видел много ответов на StackOverflow, где люди говорят, чтобы вызвать CXCallDirectoryManager.reloadExtension , чтобы перезагрузить расширение через код.Но я не знаю, где написать этот код или откуда я должен вызвать этот reloadExtension из моего проекта.
Обновление -1 Вот как я подошел.Ниже мой код view controller .
@IBAction func add(_ sender: Any) {
//let defaults = UserDefaults.standard
let userDefaults = UserDefaults(suiteName: "group.com.number1")
var finArray = userDefaults!.object(forKey: "attribute") as? [Int64] ?? [Int64]()
let number1 = number.text!
finArray.append(Int64(number1)!)
print("from main add")
print(finArray)
//let userDefaults = UserDefaults(suiteName: "group.com.number1")
userDefaults!.set(finArray, forKey: "attribute")
CXCallDirectoryManager.sharedInstance.reloadExtension(withIdentifier: "com.akshat.Blocking-array.Callblockarray", completionHandler: {(error) -> Void in if let error = error {
print("akshat"+error.localizedDescription)
}})
}
Вот мой код расширение callkit
// CallDirectoryHandler.swift
import Foundation
import CallKit
import CoreData
class CallDirectoryHandler: CXCallDirectoryProvider {
override func beginRequest(with context: CXCallDirectoryExtensionContext) {
context.delegate = self
print("inside beginrequest")
// let defaults = UserDefaults(suiteName: "group.com.number1")
// //(suiteName: "group.tag.number")
// let array = defaults!.object(forKey: "attribute") as? [Int64] ?? [Int64]()
// print(array)
// Check whether this is an "incremental" data request. If so, only provide the set of phone number blocking
// and identification entries which have been added or removed since the last time this extension's data was loaded.
// But the extension must still be prepared to provide the full set of data at any time, so add all blocking
// and identification phone numbers if the request is not incremental.
if context.isIncremental {
print("insideif")
addOrRemoveIncrementalBlockingPhoneNumbers(to: context)
print("insideif")
addOrRemoveIncrementalIdentificationPhoneNumbers(to: context)
} else {
addAllBlockingPhoneNumbers(to: context)
print("inside else")
addAllIdentificationPhoneNumbers(to: context)
}
context.completeRequest()
}
private func addAllBlockingPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
// Retrieve all phone numbers to block from data store. For optimal performance and memory usage when there are many phone numbers,
// consider only loading a subset of numbers at a given time and using autorelease pool(s) to release objects allocated during each batch of numbers which are loaded.
//
// Numbers must be provided in numerically ascending order.
print("func addAllBlockingPhoneNumbers")
let defaults = UserDefaults(suiteName: "group.com.number1")
//(suiteName: "group.tag.number")
var array = defaults!.object(forKey: "attribute") as? [Int64] ?? [Int64]()
array.sort()
print(array)
let allPhoneNumbers: [CXCallDirectoryPhoneNumber] = array
for phoneNumber in allPhoneNumbers {
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
}
}
private func addOrRemoveIncrementalBlockingPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
// Retrieve any changes to the set of phone numbers to block from data store. For optimal performance and memory usage when there are many phone numbers,
// consider only loading a subset of numbers at a given time and using autorelease pool(s) to release objects allocated during each batch of numbers which are loaded.
print("addOrRemoveIncrementalBlockingPhoneNumbers")
let defaults = UserDefaults(suiteName: "group.com.number1")
//(suiteName: "group.tag.number")
var array = defaults!.object(forKey: "attribute") as? [Int64] ?? [Int64]()
array.sort()
print(array)
let phoneNumbersToAdd: [CXCallDirectoryPhoneNumber] = array
for phoneNumber in phoneNumbersToAdd {
print(phoneNumber)
context.addBlockingEntry(withNextSequentialPhoneNumber: phoneNumber)
}
let phoneNumbersToRemove: [CXCallDirectoryPhoneNumber] = [ 1_877_555_5555 ]
for phoneNumber in phoneNumbersToRemove {
context.removeBlockingEntry(withPhoneNumber: phoneNumber)
}
// Record the most-recently loaded set of blocking entries in data store for the next incremental load...
}
private func addAllIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
// Retrieve phone numbers to identify and their identification labels from data store. For optimal performance and memory usage when there are many phone numbers,
// consider only loading a subset of numbers at a given time and using autorelease pool(s) to release objects allocated during each batch of numbers which are loaded.
//
// Numbers must be provided in numerically ascending order.
print("addAllIdentificationPhoneNumbers")
let allPhoneNumbers: [CXCallDirectoryPhoneNumber] = [ 1_877_555_5555, 1_888_555_5555 ]
let labels = [ "Telemarketer", "Local business" ]
for (phoneNumber, label) in zip(allPhoneNumbers, labels) {
context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: label)
}
}
private func addOrRemoveIncrementalIdentificationPhoneNumbers(to context: CXCallDirectoryExtensionContext) {
print(addOrRemoveIncrementalIdentificationPhoneNumbers)
// Retrieve any changes to the set of phone numbers to identify (and their identification labels) from data store. For optimal performance and memory usage when there are many phone numbers,
// consider only loading a subset of numbers at a given time and using autorelease pool(s) to release objects allocated during each batch of numbers which are loaded.
let phoneNumbersToAdd: [CXCallDirectoryPhoneNumber] = [ 1_408_555_5678 ]
let labelsToAdd = [ "New local business" ]
for (phoneNumber, label) in zip(phoneNumbersToAdd, labelsToAdd) {
context.addIdentificationEntry(withNextSequentialPhoneNumber: phoneNumber, label: label)
}
let phoneNumbersToRemove: [CXCallDirectoryPhoneNumber] = [ 1_888_555_5555 ]
for phoneNumber in phoneNumbersToRemove {
context.removeIdentificationEntry(withPhoneNumber: phoneNumber)
}
// Record the most-recently loaded set of identification entries in data store for the next incremental load...
}
}
extension CallDirectoryHandler: CXCallDirectoryExtensionContextDelegate {
func requestFailed(for extensionContext: CXCallDirectoryExtensionContext, withError error: Error) {
print("CXCallDirectoryExtensionContext")
// An error occurred while adding blocking or identification entries, check the NSError for details.
// For Call Directory error codes, see the CXErrorCodeCallDirectoryManagerError enum in <CallKit/CXError.h>.
//
// This may be used to store the error details in a location accessible by the extension's containing app, so that the
// app may be notified about errors which occured while loading data even if the request to load data was initiated by
// the user in Settings instead of via the app itself.
}
}
Но все же, этоработает только иногда.Расширение каталога вызовов занимает слишком много времени, чтобы обновлять новые номера всякий раз, когда я их добавляю.Например: если я напишу номер «А» и нажму кнопку «Добавить», будет вызвана эта функция добавления, и номер «А» будет заблокирован.Теперь, если я добавлю еще один номер, скажем, «B», расширение телефонного справочника не сможет его добавить, и B не будет заблокирован.И теперь, если добавить еще один номер «C», все будет заблокировано.Я действительно не понимаю этого.Я надеюсь, что кто-то может мне помочь.