DefaultCalendarForNewEvents не удалось
Когда я пытаюсь вызвать [newEventStore defaultCalendarForNewEvents], он возвращает сообщение об ошибке:
[707:907] defaultCalendarForNewEvents failed: Error Domain=EKCADErrorDomain Code=1013 "The operation couldn’t be completed. (EKCADErrorDomain error 1013.)"
[707:907] Error!Failed to save appointment. Description:Error Domain=EKErrorDomain Code=1 "No calendar has been set." UserInfo=0x1fc679f0 {NSLocalizedDescription=No calendar has been set.}
Приложение работает в течение длительного времени. Эта проблема пришла ко мне в первый раз. В телефоне работает IOS6 Beta4. модель - iphone 4.
Кто-нибудь знает, когда метод defaultCalendarForNewEvents окажется неудачным? Я не могу получить полезную информацию от googling.
Ответы
Ответ 1
В iOS6 Apple представила новый элемент управления конфиденциальности, который позволяет пользователю контролировать доступность контактов и каландров для каждого приложения. Итак, на стороне кода вам нужно добавить способ запроса. В iOS5 или ранее мы всегда можем вызвать
EKEventStore *eventStore = [[[EKEventStore alloc] init] autorelease];
if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
// code here for when the user allows your app to access the calendar
[self performCalendarActivity:eventStore];
} else {
// code here for when the user does NOT allow your app to access the calendar
}
}];
} else {
// code here for iOS < 6.0
[self performCalendarActivity:eventStore];
}
Ответ 2
Приложение IOS не сможет получить какие-либо данные из Календаря в системе iOS6, если вы не вызываете функцию - requestAccessToEntityType: завершение:, чтобы вызвать диалог, чтобы попросить ваших пользователей предоставить вам доступ приложение для доступа к календарю/напоминанию. Код будет выглядеть так:
//CalendarEventHandler.h
@interface CalendarEventHandler : NSObject
{
EKEventStore *eventStore;
}
@property (nonatomic, strong) EKEventStore *eventStore;
//CalendarEventHandler.m
self.eventStore =[[EKEventStore alloc] init];
if([self checkIsDeviceVersionHigherThanRequiredVersion:@"6.0"]) {
[self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- codes here when user allow your app to access theirs' calendar.
}else
{
//----- codes here when user NOT allow your app to access the calendar.
}
}];
}else {
//---- codes here for IOS < 6.0.
}
//Ниже приведен блок для проверки текущей версии ios выше требуемой.
- (BOOL)checkIsDeviceVersionHigherThanRequiredVersion:(NSString *)requiredVersion
{
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
if ([currSysVer compare:requiredVersion options:NSNumericSearch] != NSOrderedAscending)
{
return YES;
}
return NO;
}
Ответ 3
iOS6+
требует аутентификации пользователей для сохранения события в своем календаре устройства.
Вот код snippt:
// save to iphone calendar
EKEventStore *eventStore = [[EKEventStore alloc] init];
if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
{
// iOS 6 and later
// This line asks user permission to access his calendar
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted) // user user is ok with it
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = aTitle;
event.allDay = YES;
NSDateFormatter *dateFormat = [[UIApplicationSingleton sharedManager] aDateFormatter];
[dateFormat setDateFormat:@"MMM dd, yyyy hh:mm aaa"];
event.startDate = event.endDate = //put here if start and end dates are same
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
if(err)
NSLog(@"unable to save event to the calendar!: Error= %@", err);
}
else // if he does not allow
{
[[[UIAlertView alloc]initWithTitle:nil message:alertTitle delegate:nil cancelButtonTitle:NSLocalizedString(@"plzAlowCalendar", nil) otherButtonTitles: nil] show];
return;
}
}];
}
// iOS < 6
else
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = aTitle;
event.allDay = YES;
NSDateFormatter *dateFormat = [[UIApplicationSingleton sharedManager] aDateFormatter];
[dateFormat setDateFormat:@"MMM dd, yyyy hh:mm aaa"];
event.startDate = event.endDate = //put here if start and end dates are same
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
if(err)
NSLog(@"unable to save event to the calendar!: Error= %@", err);
}
И проверьте мои this post
, если у вас возникли проблемы с настройкой тревоги для приложения.
Ответ 4
решаемая.
Я случайно отключил доступ приложения к календарю в настройке- > Конфиденциальность на IOS6
Ответ 5
Быстрая форма
(на основе ответа @yunas)
_estore = EKEventStore()
_estore.reset()
_estore.requestAccessToEntityType(EKEntityTypeEvent) { (granted, error) in
if granted {
println("allowed")
/* ... */
} else {
println("not allowed")
}
}
Откроется всплывающее окно "Доступ"
Ответ 6
У меня была та же проблема, но, наконец, я нашел причину.
Мое дело было добавить события напоминания и календаря, но я использовал один EKEventStore
. В конце я разделил их и проблема исчезла:
private static let calendarEventStore = EKEventStore()
private static let remindersEventStore = EKEventStore()
Итак, теперь я использую calendarEventStore
для всех вещей, связанных с событием календаря, и remindersEventStore
для напоминания.
-
По-моему, это связано с тем, что я запросил defaultCalendarForNewEvents
и defaultCalendarForNewReminders()
в одном объекте EKEventStore
.
Также этот из EKEventStore
docs:
События, напоминания и объекты календаря, извлеченные из хранилища событий не может использоваться с каким-либо другим хранилищем событий
Ответ 7
Перейдите к настройкам Simulator/Device/Privacy/Calendars/YourApp Нажмите "ВКЛ", чтобы разрешить доступ к календарю.
И повторите свой код. Он будет работать.
Ответ 8
Для пользователей Xamarin:
EKEventStore eventStore = new EKEventStore();
eventStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) =>
{
if (granted)
{
//Your code here when user gief permissions
}
});