OStack程序员社区-中国程序员成长平台

标题: ios - 将事件添加到 iOS 7 日历 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 05:55
标题: ios - 将事件添加到 iOS 7 日历

在我的应用程序中,我必须向 iOS 7 日历添加一个事件。我在 iOS 6 中制作了一个类似的应用程序,我使用了以下代码:

CalendarUtility.h

#import <EventKit/EventKit.h>
#import <Foundation/Foundation.h>

@interface CalendarUtility : NSObject

- (void)setupEventForCalendarWithEventEKEvent*)event andEventStoreEKEventStore*)eventStore andCellDateTimeNSString*) cellDateTime;
- (void)deleteEventFromCalendarWithCellIDint)cellID;

+ (NSString*)getMonthStringFromMonthNumberNSString*)monthNumber;
+ (NSString*)getMonthNumberFromMonthStringNSString*)monthString;

@end

CalendarUtility.m

#import "CalendarUtility.h"

@interface CalendarUtility() {
    NSMutableArray *arrayofEventId;
}
@end

@implementation CalendarUtility
- (id)init {
    self = [super init];
    if (self) {
        arrayofEventId = [[NSMutableArray alloc]init];
    }
    return self;
}

- (void)setupEventForCalendarWithEventEKEvent*)event andEventStoreEKEventStore*)eventStore andCellDateTimeNSString*) cellDateTime {
    NSString *dayMonth = [cellDateTime substringToIndex:6];
    NSString *month = [dayMonth substringFromIndex:3];

    NSString *dateWithMonthNumber = [cellDateTime stringByReplacingOccurrencesOfString:[CalendarUtility  getMonthStringFromMonthNumber: [CalendarUtility getMonthNumberFromMonthString:month]] withString:[CalendarUtility getMonthNumberFromMonthString:month]];

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

    NSDate *date = [dateFormat dateFromString: dateWithMonthNumber];

    event.startDate = date;
    event.endDate = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:date];
    NSArray *arrAlarm = [NSArray arrayWithObject:[EKAlarm alarmWithAbsoluteDate:date]];
    event.alarms = arrAlarm;

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

    NSString *str = [[NSString alloc] initWithFormat"%@", event.eventIdentifier];
    [arrayofEventId addObject:str];
}

- (void)deleteEventFromCalendarWithCellIDint)cellID {
    EKEventStore* store = [[EKEventStore alloc] init];
    EKEvent* eventToRemove;
    NSString *str;
    if (cellID == 0) {
        eventToRemove = [store eventWithIdentifier:[arrayofEventId objectAtIndex:0]];
        str = [[NSString alloc] initWithFormat"%@", eventToRemove.eventIdentifier];
    } else {
        eventToRemove = [store eventWithIdentifier:[arrayofEventId objectAtIndex:1]];
        str = [[NSString alloc] initWithFormat"%@", eventToRemove.eventIdentifier];
    }
    if (eventToRemove != nil) {
        NSError* error = nil;
        [store removeEvent:eventToRemove span:EKSpanThisEvent error:&error];
    }
}

+ (NSString*)getMonthStringFromMonthNumber:(NSString*)monthNumber {
    if ([monthNumber isEqualToString"01"]) {
        return @"Gen";
    }
    if ([monthNumber isEqualToString"02"]) {
        return @"Feb";
    }
    if ([monthNumber isEqualToString"03"]) {
        return @"Mar";
    }
    if ([monthNumber isEqualToString"04"]) {
        return @"Apr";
    }
    if ([monthNumber isEqualToString"05"]) {
        return @"Mag";
    }
    if ([monthNumber isEqualToString"06"]) {
        return @"Giu";
    }
    if ([monthNumber isEqualToString:@"07"]) {
        return @"Lug";
    }
    if ([monthNumber isEqualToString:@"08"]) {
        return @"Set";
    }
    if ([monthNumber isEqualToString:@"09"]) {
        return @"Ott";
    }
    if ([monthNumber isEqualToString:@"10"]) {
        return @"Nov";
    }
    if ([monthNumber isEqualToString:@"11"]) {
        return @"Gen";
    }
    if ([monthNumber isEqualToString:@"12"]) {
        return @"Dic";
    }
    return @"0";
}

+ (NSString*)getMonthNumberFromMonthString:(NSString*)monthString {
    monthString = [monthString capitalizedString];
    if ([monthString isEqualToString:@"Gen"]) {
        return @"01";
    }
    if ([monthString isEqualToString:@"Feb"]) {
        return @"02";
    }
    if ([monthString isEqualToString:@"Mar"]) {
        return @"03";
    }
    if ([monthString isEqualToString:@"Apr"]) {
        return @"04";
    }
    if ([monthString isEqualToString:@"Mag"]) {
        return @"05";
    }
    if ([monthString isEqualToString:@"Giu"]) {
        return @"06";
    }
    if ([monthString isEqualToString:@"Lug"]) {
        return @"07";
    }
    if ([monthString isEqualToString:@"Ago"]) {
        return @"08";
    }
    if ([monthString isEqualToString:@"Set"]) {
        return @"09";
    }
    if ([monthString isEqualToString:@"Ott"]) {
        return @"10";
    }
    if ([monthString isEqualToString:@"Nov"]) {
        return @"11";
    }
    if ([monthString isEqualToString:@"Dic"]) {
        return @"12";
    }
    return 0;
}

@end

在需要将事件添加到日历的 Controller 中,我使用了以下代码:

向日历添加事件的方法

- (void) addEventToCalendar:(EpisodeCell*)cell andCell:(int)cellID {
    if ([cell.enableDisableNotification isOn]) {
        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)
                    {
                        NSString *errorMessage = [NSString stringWithFormat:@"Errore: %@", error];
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"InteracTV" message:errorMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                        [alert show];
                    }
                    else if (!granted)
                    {
                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"InteracTV" message:@"Impossibile accedere al calendario: controlla le impostazioni di privacy"delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                        [alert show];
                    }
                    else
                    {
                        // access granted
                        EKEvent *event = [EKEvent eventWithEventStore:eventStore];
                        event.title = cellTitle;

                        if (cellID == 0) {
                            [calendarUtility setupEventForCalendarWithEvent:event andEventStore:eventStore andCellDateTime:cellDateTime1];

                            [self animationForInsertedEventInCalendar];

                        } else {
                            [calendarUtility setupEventForCalendarWithEvent:event andEventStore:eventStore andCellDateTime:cellDateTime2];

                            [self animationForInsertedEventInCalendar];
                        }
                    }
                });
            }];
        }
        else
        {
            // this code runs in iOS 4 or iOS 5
            EKEvent *event = [EKEvent eventWithEventStore:eventStore];
            event.title = cellTitle;

            if (cellID == 0) {
                [calendarUtility setupEventForCalendarWithEvent:event andEventStore:eventStore andCellDateTime:cellDateTime1];

                [self animationForInsertedEventInCalendar];

            } else {
                [calendarUtility setupEventForCalendarWithEvent:event andEventStore:eventStore andCellDateTime:cellDateTime2];

                [self animationForInsertedEventInCalendar];
            }
        }

//            // PARTE PER iOS < 6 NON IMPLEMENTATO
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Bitmama iTv" message:@"Aggiorna il dispositivo almeno ad iOS 6 se vuoi aggiungere un evento al calendario." delegate:nil cancelButtonTitle:nil otherButtonTitles:@"Ok", nil];
//        [alert show];

    } else {
        [calendarUtility deleteEventFromCalendarWithCellID:cellID];
        [self animationForDeletedEventFromCalendar];
    }
}

- (void)animationForInsertedEventInCalendar {
    [UIView transitionWithView:self.imageViewOk duration:0.5 options:UIViewAnimationOptionAllowAnimatedContent animations:^(void){ [self.imageViewOk setAlpha:1.0]; } completion:^(BOOL finished)
     {
         [UIView transitionWithView:self.imageViewOk
                           duration:0.5 options:UIViewAnimationOptionAllowAnimatedContent
                         animations:^(void){ [self.imageViewOk setAlpha:0.0]; } completion:nil];
     }];
}

- (void)animationForDeletedEventFromCalendar {
    [UIView transitionWithView:self.imageViewDelete duration:0.5 options:UIViewAnimationOptionAllowAnimatedContent animations:^(void){ [self.imageViewDelete setAlpha:1.0]; } completion:^(BOOL finished)
     {
         [UIView transitionWithView:self.imageViewDelete
                           duration:0.5 options:UIViewAnimationOptionAllowAnimatedContent
                         animations:^(void){ [self.imageViewDelete setAlpha:0.0]; } completion:nil];
     }];
}

当我尝试在我的 iOS 7 新应用程序中使用此代码并使用断点对其进行调试时,它从不执行方法 - (void) addEventToCalendar:(EpisodeCell*)cell andCell:(int)cellID。 这是为什么?我的代码有什么问题?



Best Answer-推荐答案


对于将事件添加到 native 日历, 包括这两个标题

 - #import <EventKit/EventKit.h>
 - #import <EventKitUI/EventKitUI.h>

然后添加这些代码,

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

[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
 {
     if (granted)
     {
         EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
         NSString * NoteDetails =@"Event detail";

         NSDate *startDate = [NSDate date];

         //Create the end date components
         NSDateComponents *tomorrowDateComponents = [[NSDateComponents alloc] init];
         tomorrowDateComponents.day = 1;

         NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:tomorrowDateComponents
                                                                         toDate:startDate
                                                                        options:0];

         event.title =@"Your Event TITLE";
         event.startDate=startDate;
         event.endDate=endDate;
         event.notes = appointmentDetail;
         event.allDay=YES;

         [event setCalendar:[eventStore defaultCalendarForNewEvents]];

         NSError *err;
         [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
     }
     else
     {
         NSLog(@"NoPermission to access the calendar");
     }

 }];

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






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4