やりたいこと
iOS アプリからカレンダーにイベントを追加したい。
準備
下記フレームワークを追加します。
EventKit.framework
EventKitUI.framework
使用するクラス
EKEventStore
イベントやリマインダーなど、カレンダー機能にアクセスする際に必要なクラス。生成のコストが大きいのでシングルトンクラスを作ってそこで持たせるのがいいらしい。
EKEvent
イベントを表すクラス。イベントの件名や時刻などを設定する。
EKEventEditViewController
イベントを作成・修正する際に使用する ViewController。
実装の流れ
- シングルトンクラスで EKEventStore 生成
- カレンダーのアクセス権取得
- 作成したいイベント情報を作成
- 作成するイベントの詳細を編集
- 作成したイベントを保存
シングルトンクラスで EKEventStore 生成
生成は普通に alloc init で。
self.eventStore = [[EKEventStore alloc] init];
カレンダーのアクセス権取得
カレンダー機能を使用するにはユーザーの許可が必要です。 下記のようにしてユーザーから許可を得ます。
EKEventStore *eventStore = [[SingletonClass sharedInstance] eventStore];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error){
if(granted){
// ユーザーから許可が得たらここにくる。
}else{
// 許可が得られなかったらここにくる。エラーダイアログとか出す。
}
}];
}
ちなみにカレンダーのアクセス権は後から、iPhone の「設定」 → 「プライバシー」 → 「カレンダー」で変更が可能です。
作成したいイベント情報を作成
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = 'イベントタイトル';
event.startDate = [NSDate date]; //イベント開始時刻;
event.endDate = [NSDate dateWithTimeIntervalSinceNow:60*60*2];//イベント終了時刻;
作成するイベントの詳細を編集
EKEventEditViewController を使います。EKEventEditViewController の見た目を変更したい場合は、UINavigationControllerDelegate を使用します。
EKEventEditViewController* controller = [[EKEventEditViewController alloc]
init];
controller.eventStore = [[SingletonClass sharedInstance] eventStore];
controller.event = event;
controller.delegate = self; // 見た目を変更するのに使用
controller.editViewDelegate = self; //
[self presentViewController:controller animated:YES completion:nil];
作成したイベントを保存
EKEventEditViewController での操作完了時、EKEventEditViewDelegate の eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action が発火します。保存が行われた場合は保存の処理を行い、ViewController を閉じます。
- (void)eventEditViewController:(EKEventEditViewController *)controller
didCompleteWithAction:(EKEventEditViewAction)action{
NSError *error = nil;
switch (action) {
case EKEventEditViewActionCanceled:
break;
case EKEventEditViewActionSaved:
[controller.eventStore saveEvent:controller.event span:EKSpanThisEvent error:&error];
break;
case EKEventEditViewActionDeleted:
break;
default:
break;
}
[controller dismissViewControllerAnimated:YES completion:nil];
}
参考にしたページ
「カレンダーとリマインダーのプログラミングガイド」