- 创建意图处理类:
- 首先创建一个意图处理类,继承自
INSIntentHandling
协议相关的子类,例如INCreateToDoIntentHandling
。
- 假设项目已经配置好SiriKit相关的
Intents
扩展目标。
- 代码示例:
#import "INCreateToDoIntentHandling.h"
@interface MyCreateToDoIntentHandler : NSObject <INCreateToDoIntentHandling>
@end
@implementation MyCreateToDoIntentHandler
// 处理创建待办事项意图
- (void)handleCreateToDo:(INCreateToDoIntent *)intent
completion:(void (^)(INCreateToDoIntentResponse *response))completion {
// 获取待办事项标题
NSString *title = intent.title;
// 获取待办事项描述
NSString *description = intent.todoDescription;
// 获取截止时间
NSDateComponents *dueDateComponents = intent.dueDateComponents;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *dueDate = [calendar dateFromComponents:dueDateComponents];
// 这里可以添加实际创建待办事项的逻辑,例如保存到本地数据库或者同步到云端
// 示例逻辑,仅打印参数
NSLog(@"Title: %@, Description: %@, Due Date: %@", title, description, dueDate);
// 创建成功响应
INCreateToDoIntentResponse *response = [[INCreateToDoIntentResponse alloc] initWithCode:INCreateToDoIntentResponseCodeSuccess userActivity:nil];
completion(response);
}
@end
- 代码解释:
- 定义意图处理类:
MyCreateToDoIntentHandler
类实现了INCreateToDoIntentHandling
协议,负责处理创建待办事项的意图。
- 处理方法:
handleCreateToDo:completion:
方法是处理创建待办事项意图的核心方法。
- 获取参数:通过
intent.title
获取待办事项标题,intent.todoDescription
获取描述,intent.dueDateComponents
获取截止时间的日期组件,再通过NSCalendar
将日期组件转换为NSDate
类型的截止日期。
- 实际处理逻辑:在实际应用中,应将待办事项保存到合适的数据存储中,这里简单地使用
NSLog
打印参数。
- 返回响应:创建一个
INCreateToDoIntentResponse
对象,使用INCreateToDoIntentResponseCodeSuccess
表示成功处理意图,并通过completion
回调返回给系统,告知Siri操作已完成。