首页 > 解决方案 > 带有 CoreData 的 Siri 意图

问题描述

我正在构建一个小应用程序来玩车牌公路旅行游戏。我在我的应用程序中添加了一个 siri 意图,它只允许用户说“我看到 [在此处插入州名] 车牌”。我想将它与我的 CoreDataStatePlate对象连接起来,并将用户刚刚看到的车牌注册为 true for hasBeenSeen

如何结合 CoreData 和 Siri Intents 来识别用户何时说出有效的状态名称,然后将“hasBeenSeen”的值更改为 true?

PlateInfoIntentHandler

class PlateInfoIntentHandler: NSObject, PlateInfoIntentHandling {
    
    func handle(intent: PlateInfoIntent, completion: @escaping (PlateInfoIntentResponse) -> Void) {
        print(intent.stateName!)

        completion(PlateInfoIntentResponse.success(result: "Couldn't find it"))
    }
    
    func resolveStateName(for intent: PlateInfoIntent, with completion: @escaping (INStringResolutionResult) -> Void) {
        if intent.stateName == "stateName" {
            completion(INStringResolutionResult.needsValue())
        }else{
            completion(INStringResolutionResult.success(with: intent.stateName ?? ""))
        }
    }

}

StatePlate

public class StatePlate: NSManagedObject, Identifiable {
    
    // MARK: Properties
    
    @NSManaged public var id: UUID?
    @NSManaged public var name: String?
    @NSManaged public var hasBeenSeen: NSNumber?
    
    public var seen: Bool {
        get { return Bool(exactly: hasBeenSeen ?? false) ?? false }
        set {
            hasBeenSeen = NSNumber(value: newValue)
            
            do {
                try managedObjectContext?.save()                
            } catch {
                print(error.localizedDescription)
            }
        }
    }
    
    // MARK: Public Functions
    
    public static func getAllPlates() -> NSFetchRequest<StatePlate> {
        let request: NSFetchRequest<StatePlate> = StatePlate.fetchRequest() as! NSFetchRequest<StatePlate>
        let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
        request.sortDescriptors = [sortDescriptor]
        return request
    }

}

标签: swiftcore-datasiri

解决方案


推荐阅读