以编程方式在iPhone日历中添加自定义事件


Answers:


166

根据Apple文档,自iOS 6.0起,此更改有所改变。

1)您应该通过“ requestAccessToEntityType:completion:”请求访问用户日历,并在块内部执行事件处理。

2)您需要立即提交活动或将“提交”参数传递给保存/删除调用

其他一切都保持不变...

将EventKit框架添加#import <EventKit/EventKit.h>到您的代码中。

在我的示例中,我有一个NSString * savedEventId实例属性。

要添加事件:

    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"Event Title";
        event.startDate = [NSDate date]; //today
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        event.calendar = [store defaultCalendarForNewEvents];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
        self.savedEventId = event.eventIdentifier;  //save the event id if you want to access this later
    }];

删除事件:

    EKEventStore* store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];
        if (eventToRemove) {
            NSError* error = nil;
            [store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
        }
    }];

这会将事件添加到默认日历中,如果您有多个日历,那么您将找出哪个是

迅捷版

您需要导入EventKit框架

import EventKit

新增活动

let store = EKEventStore()
store.requestAccessToEntityType(.Event) {(granted, error) in
    if !granted { return }
    var event = EKEvent(eventStore: store)
    event.title = "Event Title"
    event.startDate = NSDate() //today
    event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting
    event.calendar = store.defaultCalendarForNewEvents
    do {
        try store.saveEvent(event, span: .ThisEvent, commit: true)
        self.savedEventId = event.eventIdentifier //save event id to access this particular event later
    } catch {
        // Display error to user
    }
}

移除活动

let store = EKEventStore()
store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in
    if !granted { return }
    let eventToRemove = store.eventWithIdentifier(self.savedEventId)
    if eventToRemove != nil {
        do {
            try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)
        } catch {
            // Display error to user
        }
    }
}

6
不适用于我,一切都会出错,但日历中没有事件
Boris Gafurov

一切都存储在ekevent对象中,但没有存储在日历中hlp me

1
@William T:我可以显示日历应用程序的“添加事件”屏幕(使用URL方案)并传递事件的信息,以便在出现“添加事件”屏幕时,它将具有预填充的数据。用户只需要按添加事件按钮即可。在您的示例事件中,没有向用户显示任何指示。
2014年

1
如果一切似乎正常,但没有日历出现,请检查是否存在Cloud VS Local日历。如果您同时使用Cloud和本地日历,则Cloud日历会强制隐藏本地日历。
zonabi 2014年

2
@ReddyBasha添加事件时,需要保存eventIdentifier并将其存储以备将来使用。删除时应使用该事件ID。
威廉·T。

154

您可以使用OS 4.0中的事件工具包框架来执行此操作。

右键单击窗口左侧的“组和文件”导航器中的“ FrameWorks”组。选择“添加”,然后选择“现有FrameWorks”,然后选择“ EventKit.Framework”。

然后,您应该能够使用以下代码添加事件:

#import "EventTestViewController.h"
#import <EventKit/EventKit.h>

@implementation EventTestViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    EKEventStore *eventStore = [[EKEventStore alloc] init];

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

    event.startDate = [[NSDate alloc] init];
    event.endDate   = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];

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

@end

18
感谢您发布此信息。这只是对所有阅读本文的人的提醒:请注意内存泄漏。此代码示例中有几个。此外,最佳做法还要求您在saveEvent:span:error之后检查'err'的值并相应地进行处理。
大卫·卡尼

您知道如何添加重复事件吗?像每个星期一都有活动吗?
杰伊·瓦查尼

5
以编程方式添加重复事件:请查看developer.apple.com/library/ios/#documentation/EventKit/…。另一个选择是使用框架提供的默认视图控制器来添加/编辑事件(例如Calendar At-A-Glance应用程序bit.ly/cJq4Bh)。对于此选项,请参阅developer.apple.com/library/ios/#documentation/EventKitUI/...
DenTheMan

要在XCode 4中添加框架,请参见以下SO问题:stackoverflow.com/questions/3352664/…–
Nate

1
4.0?不会飞6见上面的答案
鲍里斯·加富罗夫

13

是的,仍然没有针对此的API(2.1)。但是似乎在WWDC上,很多人(包括我自己)已经对功能感兴趣,建议您转到以下站点并为此创建功能请求。如果有足够的兴趣,他们最终可能会将ICal.framework移至公共SDK。

https://developer.apple.com/bugreporter/


5
答案已过时,请考虑将其删除
Jasper


5

您可以使用Event API(如Tristan所述)添加事件,也可以添加显示在iOS日历中的Google Calendar事件。

使用Google的API Objective-C客户端

  - (void)addAnEvent {
  // Make a new event, and show it to the user to edit
  GTLCalendarEvent *newEvent = [GTLCalendarEvent object];
  newEvent.summary = @"Sample Added Event";
  newEvent.descriptionProperty = @"Description of sample added event";

  // We'll set the start time to now, and the end time to an hour from now,
  // with a reminder 10 minutes before
  NSDate *anHourFromNow = [NSDate dateWithTimeIntervalSinceNow:60*60];
  GTLDateTime *startDateTime = [GTLDateTime dateTimeWithDate:[NSDate date]
                                                    timeZone:[NSTimeZone systemTimeZone]];
  GTLDateTime *endDateTime = [GTLDateTime dateTimeWithDate:anHourFromNow
                                                  timeZone:[NSTimeZone systemTimeZone]];

  newEvent.start = [GTLCalendarEventDateTime object];
  newEvent.start.dateTime = startDateTime;

  newEvent.end = [GTLCalendarEventDateTime object];
  newEvent.end.dateTime = endDateTime;

  GTLCalendarEventReminder *reminder = [GTLCalendarEventReminder object];
  reminder.minutes = [NSNumber numberWithInteger:10];
  reminder.method = @"email";

  newEvent.reminders = [GTLCalendarEventReminders object];
  newEvent.reminders.overrides = [NSArray arrayWithObject:reminder];
  newEvent.reminders.useDefault = [NSNumber numberWithBool:NO];

  // Display the event edit dialog
  EditEventWindowController *controller = [[[EditEventWindowController alloc] init] autorelease];
  [controller runModalForWindow:[self window]
                          event:newEvent
              completionHandler:^(NSInteger returnCode, GTLCalendarEvent *event) {
                // Callback
                if (returnCode == NSOKButton) {
                  [self addEvent:event];
                }
              }];
}

5

Swift 4.0的实现:

在页面顶部使用import import EventKit

然后

@IBAction func addtoCalendarClicked(sender: AnyObject) {

    let eventStore = EKEventStore()

    eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in

        if (granted) && (error == nil) {
            print("granted \(granted)")
            print("error \(error)")

            let event = EKEvent(eventStore: eventStore)

            event.title = "Event Title"
            event.startDate = Date()
            event.endDate = Date()
            event.notes = "Event Details Here"
            event.calendar = eventStore.defaultCalendarForNewEvents

            var event_id = ""
            do {
                try eventStore.save(event, span: .thisEvent)
                event_id = event.eventIdentifier
            }
            catch let error as NSError {
                print("json error: \(error.localizedDescription)")
            }

            if(event_id != ""){
                print("event added !")
            }
        }
    })
}

您能帮我用Google日历解决相同的问题吗@Dashrath
Dilip Tiwari

4

更新Dashrath答案的Swift 4

import UIKit
import EventKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let eventStore = EKEventStore()

        eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in

            if (granted) && (error == nil) {


                let event = EKEvent(eventStore: eventStore)

                event.title = "My Event"
                event.startDate = Date(timeIntervalSinceNow: TimeInterval())
                event.endDate = Date(timeIntervalSinceNow: TimeInterval())
                event.notes = "Yeah!!!"
                event.calendar = eventStore.defaultCalendarForNewEvents

                var event_id = ""
                do{
                    try eventStore.save(event, span: .thisEvent)
                    event_id = event.eventIdentifier
                }
                catch let error as NSError {
                    print("json error: \(error.localizedDescription)")
                }

                if(event_id != ""){
                    print("event added !")
                }
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

也不要忘记添加日历使用权限 私人设置的图像


2

Swift-4.2中的工作代码

import UIKit
import EventKit
import EventKitUI

class yourViewController: UIViewController{

    let eventStore = EKEventStore()

    func addEventToCalendar() {

    eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
        DispatchQueue.main.async {
            if (granted) && (error == nil) {
                let event = EKEvent(eventStore: self.eventStore)
                event.title = self.headerDescription
                event.startDate = self.parse(self.requestDetails.value(forKey: "session_time") as? String ?? "")
                event.endDate = self.parse(self.requestDetails.value(forKey: "session_end_time") as? String ?? "")
                let eventController = EKEventEditViewController()
                eventController.event = event
                eventController.eventStore = self.eventStore
                eventController.editViewDelegate = self
                self.present(eventController, animated: true, completion: nil)

            }
        }


       })
    }

}

现在,我们将获得事件屏幕,在这里您还可以修改设置:

在此处输入图片说明

现在添加委托方法来处理取消,并添加事件屏幕的事件按钮动作:

    extension viewController: EKEventEditViewDelegate {

    func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
        controller.dismiss(animated: true, completion: nil)

    }
}

注意:不要忘记将NSCalendarsUsageDescription键添加到info plist中。


1

请记住,将endDate设置为创建的事件,这是强制性的。

否则它将(几乎无提示)失败并显示以下错误:

"Error Domain=EKErrorDomain Code=3 "No end date has been set." UserInfo={NSLocalizedDescription=No end date has been set.}"

对我来说,完整的工作代码是:

EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
    if (!granted) { return; }
    EKEvent *calendarEvent = [EKEvent eventWithEventStore:store];
    calendarEvent.title = [NSString stringWithFormat:@"CEmprendedor: %@", _event.name];
    calendarEvent.startDate = _event.date;
    // 5 hours of duration, we must add the duration of the event to the API
    NSDate *endDate = [_event.date dateByAddingTimeInterval:60*60*5];
    calendarEvent.endDate = endDate;
    calendarEvent.calendar = [store defaultCalendarForNewEvents];
    NSError *err = nil;
    [store saveEvent:calendarEvent span:EKSpanThisEvent commit:YES error:&err];
    self.savedEventId = calendarEvent.eventIdentifier;  //saving the calendar event id to possibly deleted them
}];

1
还要记住,结束日期必须等于或大于开始日期。否则,您将得到另一个错误。
喜怒无常的

0

Google的想法很不错,但是有问题。

我可以成功打开Goog​​le日历活动屏幕-但只能在主桌面版本上打开,并且无法在iPhone Safari上正确显示。可以在Safari上正确显示的Google移动日历似乎无法与API配合使用来添加事件。

目前,我看不出有什么好办法。


0

简单....使用tapku库....您可以在Google上搜索并使用该词...它的开放源代码...很享受.....无需使用这些代码进行调试....



与压光机的应用程序事件可以Tapku库同步日历
coder1010

我所知道的是Tapku库是一个日历组件控件,它具有一个称为“数据源”的选项。因此,根据您的逻辑写您从哪里获取的源代码... Happy Coding :)
Rajesh_Bangalore
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.