在不使用CallKit的情况下,你可以使用CoreData来保存应用内呼叫的最近通话记录。下面是一个代码示例:
首先,创建一个数据模型来表示通话记录:
import Foundation
import CoreData
class CallRecord: NSManagedObject {
@NSManaged var phoneNumber: String
@NSManaged var timestamp: Date
}
然后,在你的数据管理类中,创建一个方法来保存通话记录:
import CoreData
class DataManager {
static let shared = DataManager()
private lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "YourDataModelName")
container.loadPersistentStores { (_, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
}
return container
}()
func saveCallRecord(phoneNumber: String) {
let context = persistentContainer.viewContext
let callRecord = CallRecord(context: context)
callRecord.phoneNumber = phoneNumber
callRecord.timestamp = Date()
do {
try context.save()
} catch {
print("Failed to save call record: \(error)")
}
}
func getCallRecords() -> [CallRecord] {
let context = persistentContainer.viewContext
let fetchRequest: NSFetchRequest = CallRecord.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)]
do {
let callRecords = try context.fetch(fetchRequest)
return callRecords
} catch {
print("Failed to fetch call records: \(error)")
return []
}
}
}
在保存通话记录时,调用saveCallRecord
方法:
DataManager.shared.saveCallRecord(phoneNumber: "1234567890")
在需要获取通话记录时,调用getCallRecords
方法:
let callRecords = DataManager.shared.getCallRecords()
for record in callRecords {
print("Phone number: \(record.phoneNumber), Timestamp: \(record.timestamp)")
}
这样就可以在应用内保存和获取通话记录了。注意,上述代码示例中的数据模型名字应该替换为你自己的数据模型名字。