EventKit フレームワークを使用して、iPhone カレンダーにエントリを作成する必要があります。
私のアプリは国際的でなければならないので、さまざまなタイムゾーンに注意する必要があります。私が今していること:
イベントは午前 6 時に開始する必要があります。したがって、次のコードで NSDate オブジェクトを作成しています。
[NSDate dateWithString:[NSString stringWithFormat:@"%d-%d-%d %d:%d:00 +0000",year,month,day,hour,minute]];
私が得るのは、午前6時00分とタイムゾーンGMTのNSDateオブジェクトです。
この NSDate をイベントの startDate として使用する場合、システムのタイムゾーンを使用して、イベントが実際にカレンダーに午前 6:00 として表示されるようにします。
したがって、私はこのコードを使用します:
+(NSDate*) convertToSystemTimezone:(NSDate*)sourceDate
{
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
return destinationDate;
}
例として、デバイスのタイムゾーンを NEW YORK に変更します。コードをデバッグすると、タイムゾーンと -14400 秒のオフセットが正しく認識されます。したがって、私の開始と終了の NSDate オブジェクトは正しいようです。
カレンダーを見ると、アプリは午前 6:00 ではなく午前 4:00 に開始するイベントを作成しました。
私は何を間違っていますか??
編集:イベントを作成するための私のコード:
06:00 am から 08:00 am までのイベントを作成する例
int year=2011;
int month=6;
int day=26;
int hour=6;
int minute=0;
NSDate *startDate = [NSDate dateWithString:[NSString stringWithFormat:@"%d-%d-%d %d:%d:00 +0000",year,month,day,hour, minute];
startDate=[self convertToSystemTimezone:startDate];
NSDate *endDate = [NSDate dateWithString:[NSString stringWithFormat:@"%d-%d-%d %d:%d:00 +0000",year,month,day,8, minute];
endDate=[self convertToSystemTimezone:endDate];
EKEventStore *eventDB = [[EKEventStore alloc] init];
EKEvent *myEvent = [EKEvent eventWithEventStore:eventDB];
myEvent.title = @"Testevent";
myEvent.startDate = startDate;
myEvent.endDate = endDate;
myEvent.allDay = NO;
[myEvent setCalendar:[eventDB defaultCalendarForNewEvents]];
NSError *err;
[eventDB saveEvent:myEvent span:EKSpanThisEvent error:&err];
[eventDB release];
既存のイベントの削除は示されていませんが、これはテスト済みで動作します。