iphone - 在 xcode iOS 中将事件添加到日历

标签 iphone ios calendar eventkit

你好

我有将事件添加到日历的代码,但它没有添加。

-(void)event
{
    EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
    event.title     = @"Event";


    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];


    NSString *dateandtime =[NSString stringWithFormat:@"%@%@%@",datestring,@" ",starttimestring];
    NSString *dateandtimeend =[NSString stringWithFormat:@"%@%@%@",datestring,@" ",endtimestring];



    event.startDate = [tempFormatter dateFromString:dateandtime];
    event.endDate = [tempFormatter dateFromString:dateandtimeend];


    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];

    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}

从 XML 中我得到了这种格式的日期和时间:

日期字符串:28.10.2012

开始时间字符串:15:00

最佳答案

您使用的是 iOS 6 模拟器还是运行 iOS 6 的设备?如果是这样,您需要先征得用户使用事件存储的许可,然后才能将项目保存到其中。

基本上,如果 requestAccessToEntityType:completion: 选择器在您的事件存储对象上可用,您可以调用该方法并提供一个代码块,该代码块在用户授予权限时执行,然后您将在该 block 中保存事件.

首先将 EventKit 框架添加到您的项目中,不要忘记包含导入:

#import <EventKit/EventKit.h>

这是我使用的对我有用的代码片段:

EKEventStore *eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
{
    // the selector is available, so we must be on iOS 6 or newer
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                // display error message here
            }
            else if (!granted)
            {
                // display access denied error message here
            }
            else
            {
                // access granted
                // ***** do the important stuff here *****
            }
        });
    }];
}
else
{
    // this code runs in iOS 4 or iOS 5
    // ***** do the important stuff here *****
}

[eventStore release];

这是我写的一篇关于这个主题的博文:

http://www.dosomethinghere.com/2012/10/08/ios-6-calendar-and-address-book-issues/

关于iphone - 在 xcode iOS 中将事件添加到日历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13082678/

相关文章:

ios - 无法将类型 '[String : String?]' 的值转换为预期的参数类型 '[String : AnyObject?]'

iPhone:为 SSL 连接安装证书

ios - prepareForSegue 什么时候被调用?

iphone - 如何以编程方式在 iPhone 上创建将同步到 iCal 的新日历

c# - 回历早了 1 天。

iphone - 如何将数组中的 subview 添加到 uiview 中?

ios - UINavigationBar 的 UIAppearance 在与自定义 View Controller 一起使用时无法正常工作...?

ios - 从信标退出时收到通知

ios - 当 CloudKit 错误发生时,客户端是否应该继续重新发送?

javascript - 选择另一个时重置单选按钮字段的最佳方法