当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《以编程方式在iPhone日历中添加自定义事件》经验,为你挑选了6个好方法。

有没有办法从自定义应用程序中将iCal事件添加到iPhone日历?



1> William T...:

基于Apple文档,这在iOS 6.0中有所改变.

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

2)您需要立即提交您的活动或将"提交"参数传递给您的保存/删除呼叫

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

添加EventKit框架并添加#import 到您的代码中.

在我的示例中,我有一个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];
        }
    }];

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

Swift版本

您需要导入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
        }
    }
}


对我来说不起作用,一切都没有错误但在日历中没有事件
@ReddyBasha添加事件时,需要保存eventIdentifier并存储以备将来使用.您应该在删除它时使用该事件ID.

2> WoodenKitty..:

您可以使用OS 4.0中的Event Kit框架执行此操作.

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

然后你应该能够添加如下代码的事件:

#import "EventTestViewController.h"
#import 

@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


感谢发布此内容.只是提醒所有阅读此内容的人:注意观察内存泄漏.这段代码示例中有几个.此外,最佳实践将要求您在saveEvent:span:error之后检查'err'的值并相应地处理事情.
以编程方式添加重复事件:请查看http://developer.apple.com/library/ios/#documentation/EventKit/Reference/EKRecurrenceRuleClassRef/Reference/Reference.html#//apple_ref/doc/c_ref/EKRecurrenceRule.另一种选择是使用默认框架提供的视图控制器来添加/编辑事件(例如Calendar At-A-Glance应用程序http://bit.ly/cJq4Bh).有关此选项,请参阅http://developer.apple.com/library/ios/#documentation/EventKitUI/Reference/EKEventEditViewControllerClassRef/Reference/Reference.html

3> keremk..:

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

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


答案已过时,请考虑删除此内容

4> Chris S..:

iPhone OS 4.0中添加了日历访问:

日历访问
应用程序现在可以使用Event Kit直接在日历应用程序中创建和编辑事件.
创建定期事件,设置开始和结束时间并将其分配给设备上的任何日历.



5> Iggy..:

您可以使用像Tristan概述的事件API添加事件,还可以添加显示在iOS日历中的Google日历事件.

使用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];
                }
              }];
}



6> Dashrath..:

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 !")
            }
        }
    })
}

推荐阅读
有风吹过best
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有