2014-01-14 45 views
2

我在應用程序中添加了以下代碼。如果[comps setYear:1]工作正常,但如果我將年份值更改爲2或大於2,代碼不會顯示任何錯誤但也不在日曆中添加任何事件。這僅發生在iOS 7中。但是如果我在iOS 6上運行相同的代碼,則其正常工作&事件會成功添加到日曆中。 iOS 7中是否有添加未來事件的限制?EventKit saveEvent在iOS 7中無法正常工作

-(void)addEvent{ 
    EKEventStore *es = [[EKEventStore alloc] init]; 
    EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent]; 
    BOOL needsToRequestAccessToEventStore = (authorizationStatus == EKAuthorizationStatusNotDetermined); 

    if (needsToRequestAccessToEventStore) { 
     [es requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) { 
      if (granted) { 
       [self setEventForStore:es]; 
      } else { 

      } 
     }]; 
    } else { 
     BOOL granted = (authorizationStatus == EKAuthorizationStatusAuthorized); 
     if (granted) { 
      [self setEventForStore:es]; 


     } else { 

     } 
    } 
} 

-(void)setEventForStore:(EKEventStore*)store{ 
    EKEvent *event = [EKEvent eventWithEventStore:store]; 
    event.title = @"Event 4"; 

    NSCalendar *calendar = [NSCalendar currentCalendar]; 
    NSDateComponents *comps = [NSDateComponents new]; 
    // comps.day =3650; 
    comps.day=5; 
    comps.hour=1; 
    comps.year=2; 
    NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; 
    event.startDate = sevenDays; 

    NSDate *sevenDays1 = [event.startDate dateByAddingTimeInterval:60*60];; 
    // duration = 1 h 
    event.endDate = sevenDays1; 

    [event setCalendar:[store defaultCalendarForNewEvents]]; 
    NSError *err = nil; 
    [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err]; 
} 
` 

回答

0

只要通過組件的日期處理,請設置它們以下列方式:

NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease]; 
[comps setDay:05]; 
[comps setMonth:01]; 
[comps setYear:2014]; //instead of adding a single digit number like so: 2 

//followed by your code... 
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; 
//... 

更新1

您剛纔說您的活動不被保存在日曆時您可以稍微調整NSDate組件中的整數值。通過NSLogging您的日期可以快速瞭解發生了什麼。在嘗試將其添加到日曆之前,請查看輸出的內容。

//Right after this below line 
NSDate *sevenDays = [calendar dateByAddingComponents:comps toDate:[NSDate date] options:0]; 

//Add the code here so we can see what `sevenDays` prints out. 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"dd-MM-yyyy"]; 
NSString *strDate = [dateFormatter stringFromDate:sevenDays]; 
NSLog(@"Seven Days date = %@", strDate); 
+0

但我的代碼工作正常,如果我設置year = 1那麼年份= 2是什麼問題?我試着用你的代碼,但仍然沒有在日曆中顯示任何事件。 – Nitin

+0

@Nitin檢查更新1,讓我知道你得到什麼。 – Pavan

+0

如果我使用[comps setDay:05]; [comps setMonth:01]; [comps setYear:2014];然後控制檯輸出是七天日期= 19-02-4028 – Nitin