void ICalendar.AddToCalendar(GenEvent genEvent) { var estZone = TimeZoneInfo.FindSystemTimeZoneById("America/Indiana/Indianapolis"); var newStartTime = TimeZoneInfo.ConvertTime(genEvent.StartDateTime, estZone, TimeZoneInfo.Local); var newEndTime = TimeZoneInfo.ConvertTime(genEvent.EndDateTime, estZone, TimeZoneInfo.Local); eventStore = eventStore ?? new EKEventStore(); eventStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => { if (granted) { EKEventStore eventStore = new EKEventStore(); //Insert the data into the agenda. EKEvent newEvent = EKEvent.FromStore(eventStore); newEvent.StartDate = CalendarHelpers.DateTimeToNSDate(newStartTime); newEvent.EndDate = CalendarHelpers.DateTimeToNSDate(newEndTime); newEvent.Title = genEvent.Title; newEvent.Notes = genEvent.Location + "\r\n\r\n" + genEvent.Description + "\r\n\r\n" + genEvent.LiveURL ; EKAlarm[] alarmsArray = new EKAlarm[1]; alarmsArray[0] = EKAlarm.FromDate(newEvent.StartDate.AddSeconds(-600)); newEvent.Alarms = alarmsArray; newEvent.Calendar = eventStore.DefaultCalendarForNewEvents; eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, true, out e); Device.BeginInvokeOnMainThread(() => { //bool returned = await GlobalVars.notifier.Notify(ToastNotificationType.Success, // "Event added!", genEvent.Title + " has been added to your calendar!", TimeSpan.FromSeconds(3)); //var returned = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Event added!", // Description = genEvent.Title + " has been added to your calendar!", //}); GlobalVars.DoToast(genEvent.Title + " has been added to your calendar!", GlobalVars.ToastType.Green); }); } //do something here else { Device.BeginInvokeOnMainThread(() => { //bool returned = await GlobalVars.notifier.Notify(ToastNotificationType.Error, // "Don't have permission!", "You need to allow this app to access the calendar first. Please change the setting in Settings -> Privacy -> Calendars.", TimeSpan.FromSeconds(4)); //var returned = await GlobalVars.notifier.Notify(new NotificationOptions() //{ // Title = "Don't have permission!", // Description = "You need to allow this app to access the calendar first. Please change the setting in Settings -> Privacy -> Calendars.", //}); GlobalVars.DoToast("Need permission - you need to allow this app to access the calendar first. Please change the setting in Settings -> Privacy -> Calendars.", GlobalVars.ToastType.Red, 5000); }); } }); }
public async Task <string> CreateAlarmAsync(string title, string description, DateTime timeInit, DateTime timeEnd, int alarmMinutes) { bool hasPermission = await ASkForPermissionsAsync(); if (!hasPermission) { return(string.Empty); } if (appCalendar == null) { await CreateCalendarForAppAlarmsAsync(); } if (appCalendar != null) { EKEvent reminder = EKEvent.FromStore(eventsStore); reminder.AddAlarm(EKAlarm.FromTimeInterval(-(alarmMinutes * 60))); reminder.StartDate = timeInit.ToNSDate(); reminder.EndDate = timeEnd.ToNSDate(); reminder.Title = title; reminder.Notes = description; reminder.Calendar = appCalendar; bool saved = eventsStore.SaveEvent(reminder, EKSpan.ThisEvent, out NSError e); if (e == null) { return(reminder.CalendarItemIdentifier); } } return(string.Empty); }
public void AddEvent(string Titulo, string Lugar, DateTime Inicio, DateTime Termina, string Descripcion) { try { EKEventStore evStore = new EKEventStore(); evStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => { if (!granted) { new UIAlertView("Acceso denegado", "El usuario no permite acceso al calendario", null, "ok", null).Show(); } }); EKCalendar calendar = evStore.DefaultCalendarForNewEvents; NSPredicate evPredicate = evStore.PredicateForEvents(Inicio, Termina, evStore.GetCalendars(EKEntityType.Event)); bool encontrado = false; evStore.EnumerateEvents(evPredicate, delegate(EKEvent calEvent, ref bool stop) { if (calEvent.Title == Titulo) { encontrado = true; } }); if (encontrado) { new UIAlertView("Evento", "El evento ya existe en el calendario", null, "ok", null).Show(); } else { EKEvent newEvent = EKEvent.FromStore(evStore); newEvent.Title = Titulo; newEvent.Notes = Descripcion; newEvent.Calendar = calendar; newEvent.StartDate = Inicio; newEvent.EndDate = Termina; newEvent.Location = Lugar; var error = new NSError(new NSString(""), 0); evStore.SaveEvent(newEvent, EKSpan.ThisEvent, out error); if (error.LocalizedDescription != "") { new UIAlertView("Evento", "Hubo un problema al agregar el evento " + error.LocalizedDescription, null, "ok", null).Show(); } else { new UIAlertView("Evento", "El evento se agregó a su calendario", null, "ok", null).Show(); } } } catch (Exception) { new UIAlertView("Evento", "Hubo un problema al agregar el evento", null, "ok", null).Show(); } }
/// <summary> /// Creates the simple event. /// </summary> /// <param name="titleTxt">Title text.</param> /// <param name="fromDate">From date.</param> /// <param name="toDate">To date.</param> public static void CreateSimpleEvent(string titleTxt, DateTime fromDate, DateTime toDate) { EKEvent newEvent = EKEvent.Event(eventStore); calendar = eventStore.defaultCalendarForNewEvents; Debug.Log("in CreateSimpleEvent, output of calendar: " + calendar); newEvent.title = titleTxt; newEvent.startDate = fromDate; newEvent.endDate = toDate; newEvent.calendar = calendar; eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, null); eventStore.SaveCalendar(calendar, true, null); eventStore.Commit(null); }
public async Task <bool> AddAppointment(MyAppointmentType appointment) { var eventStore = new EKEventStore(); var granted = await eventStore.RequestAccessAsync(EKEntityType.Event); if (granted.Item1) { EKEvent newEvent = EKEvent.FromStore(eventStore); newEvent.StartDate = DateTimeToNSDate(appointment.ExpireDate); newEvent.EndDate = DateTimeToNSDate(appointment.ExpireDate.AddHours(1)); newEvent.Title = appointment.Title; newEvent.Notes = appointment.WhereWhen; newEvent.Calendar = eventStore.DefaultCalendarForNewEvents; return(eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, out NSError e)); } return(false); }
// completed is called when a user eith public override void Completed(EventKitUI.EKEventEditViewController controller, EKEventEditViewAction action) { eventController.DismissViewController(true, null); switch (action) { case EKEventEditViewAction.Canceled: break; case EKEventEditViewAction.Deleted: break; case EKEventEditViewAction.Saved: NSError error; eventStore.SaveEvent(controller.Event, EKSpan.ThisEvent, out error); break; } }
public void AddEvent(string Titulo, string Lugar, DateTime Inicio, DateTime Termina, string Descripcion) { try { EKEventStore evStore = new EKEventStore(); evStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => { if (!granted) new UIAlertView("Acceso denegado", "El usuario no permite acceso al calendario", null, "ok", null).Show(); }); EKCalendar calendar = evStore.DefaultCalendarForNewEvents; NSPredicate evPredicate = evStore.PredicateForEvents(Inicio, Termina, evStore.GetCalendars(EKEntityType.Event)); bool encontrado = false; evStore.EnumerateEvents(evPredicate, delegate(EKEvent calEvent, ref bool stop) { if (calEvent.Title == Titulo) encontrado = true; }); if (encontrado) { new UIAlertView("Evento", "El evento ya existe en el calendario", null, "ok", null).Show(); } else { EKEvent newEvent = EKEvent.FromStore(evStore); newEvent.Title = Titulo; newEvent.Notes = Descripcion; newEvent.Calendar = calendar; newEvent.StartDate = Inicio; newEvent.EndDate = Termina; newEvent.Location = Lugar; var error = new NSError(new NSString(""), 0); evStore.SaveEvent(newEvent, EKSpan.ThisEvent, out error); if(error.LocalizedDescription!="") new UIAlertView("Evento", "Hubo un problema al agregar el evento " + error.LocalizedDescription, null, "ok", null).Show(); else new UIAlertView("Evento", "El evento se agregó a su calendario", null, "ok", null).Show(); } } catch (Exception) { new UIAlertView("Evento", "Hubo un problema al agregar el evento", null, "ok", null).Show(); } }
public bool AddToCalendar(CalendarModel calendarModel) { //var granted = EventStore.RequestAccessAsync(EKEntityType.Event); EventStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => { if (granted) { EKEvent newEvent = EKEvent.FromStore(EventStore); newEvent.Title = calendarModel.Title; newEvent.Notes = calendarModel.Description; newEvent.StartDate = (NSDate)calendarModel.Start; newEvent.EndDate = (NSDate)calendarModel.End; newEvent.Location = calendarModel.Location; newEvent.Calendar = EventStore.DefaultCalendarForNewEvents; EventStore.SaveEvent(newEvent, EKSpan.ThisEvent, out e); return; } new UIAlertView("Access Denied,", "User Denied Access to Calendar Data", null, "ok", null).Show(); Debug.WriteLine(e); }); return(true); }
// Implementación de la interfaz public async Task <string> CreateEventCalendar(string titulo, string descripcion, DateTime inicioEvento, DateTime finEvento) { TaskCompletionSource <string> tcs = new TaskCompletionSource <string>(); if (permisoOtorgado) { EKEvent newEvent = EKEvent.FromStore(eventStore); newEvent.StartDate = inicioEvento.ToNSDate(); newEvent.EndDate = finEvento.ToNSDate(); newEvent.Title = titulo; newEvent.Notes = descripcion; newEvent.AllDay = true; newEvent.Calendar = eventStore.DefaultCalendarForNewEvents; NSError e; eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, out e); tcs.SetResult("true"); } else { tcs.SetResult(string.Empty); } return(await tcs.Task); }
/// <summary> /// Creates new reminder about medicine /// </summary> /// <param name="Name">Name of medicine</param> /// <param name="time">Time of taking medicine</param> public void AddReminder(string Name, NSDate time) { /* * EKReminder reminder = EKReminder.Create(eventStore); * reminder.Title = Name; * NSError e = new NSError(); * EKAlarm timeToRing = new EKAlarm(); * timeToRing.AbsoluteDate = time; * reminder.Calendar = eventStore.DefaultCalendarForNewReminders; * reminder.AddAlarm(timeToRing); * //reminder.Calendar = eventStore.DefaultCalendarForNewReminders; * eventStore.SaveReminder(reminder, true, out e); */ eventStore.RequestAccess(EKEntityType.Event, (bool granted, NSError e) => { if (granted) { EKEvent newEvent = EKEvent.FromStore(eventStore); newEvent.StartDate = (NSDate)DateTime.Now; newEvent.EndDate = (NSDate)DateTime.Now.AddMinutes(5); newEvent.Title = Name; newEvent.Calendar = eventStore.DefaultCalendarForNewEvents; eventStore.SaveEvent(newEvent, EKSpan.ThisEvent, out e); } //do something here else { var okAlertController = UIAlertController.Create("Error", "Application doesnt have permission for calendar.", UIAlertControllerStyle.Alert); okAlertController.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, null)); PresentViewController(okAlertController, true, null); } }); }
public async Task PushMeetingsToCalendarAsync(List <Meeting> meetings) { try { using (await _PushMeetingsToCalendarAsyncLock.LockAsync()) { if (!(await _eventStore.RequestAccessAsync(EKEntityType.Event)).Item1) { return; } var calendar = _eventStore.GetCalendar(AcraCalendarIdentifier); CGColor colorToUse = null; if (calendar != null) { colorToUse = calendar.CGColor; NSError errorToDelete;; _eventStore.RemoveCalendar(calendar, true, out errorToDelete); } var otherToDelete = _eventStore.GetCalendars(EKEntityType.Event).Where(c => c.Title.StartsWith("ACRA")); foreach (var item in otherToDelete) { NSError errorToDelete; _eventStore.RemoveCalendar(item, true, out errorToDelete); } // now recreate a calendar ! calendar = EKCalendar.FromEventStore(_eventStore); calendar.Title = "ACRA du " + DateTime.Now.ToString("g", new System.Globalization.CultureInfo("fr")); if (colorToUse != null) { calendar.CGColor = colorToUse; } EKSource[] sources = _eventStore.Sources; var sourceToSet = sources .FirstOrDefault(s => s.SourceType == EKSourceType.CalDav && s.Title.Equals("iCloud", StringComparison.InvariantCultureIgnoreCase)); if (sourceToSet == null) { sourceToSet = sources.FirstOrDefault(s => s.SourceType == EKSourceType.Local); } if (sourceToSet == null) { sourceToSet = _eventStore.DefaultCalendarForNewEvents.Source; } calendar.Source = sourceToSet; NSError error; _eventStore.SaveCalendar(calendar, true, out error); AcraCalendarIdentifier = calendar.CalendarIdentifier; var toSaves = meetings.OrderByDescending(ap => ap.StartDate).ToArray(); var howMuch = toSaves.Length; for (int index = 0; index < howMuch; index++) { var appointData = toSaves[index]; var toSave = EKEvent.FromStore(_eventStore); //if (!string.IsNullOrEmpty(appointData.)) //{ // toSave.Location = appointData.Location; //} toSave.StartDate = ConvertDateTimeToNSDate(appointData.StartDate); toSave.AllDay = appointData.AllDayEvent; if (appointData.IsRecurrent && appointData.AllDayEvent) { var end = EKRecurrenceEnd.FromEndDate(ConvertDateTimeToNSDate(appointData.EndDate)); var rule = new EKRecurrenceRule(EKRecurrenceFrequency.Weekly, 1, end); toSave.RecurrenceRules = new[] { rule }; } else { toSave.EndDate = ConvertDateTimeToNSDate(appointData.EndDate); } // If set to AllDay and given an EndDate of 12am the next day, EventKit // assumes that the event consumes two full days. // (whereas WinPhone/Android consider that one day, and thus so do we) // if (appointData.AllDayEvent) { toSave.EndDate = ConvertDateTimeToNSDate(appointData.EndDate.AddDays(-1)); } if (!appointData.IsHoliday) { if (appointData.Duration.TotalDays > 1 && !appointData.IsRecurrent) { toSave.Title = ((int)appointData.Duration.TotalDays + 1) + " " + appointData.Title; } else { toSave.Title = appointData.Title; } } else { //TODO : localisation toSave.Title = "[FERIE] " + appointData.Title; } toSave.Notes = appointData.Type.ToString(); toSave.Calendar = calendar; NSError errorCommit; _eventStore.SaveEvent(toSave, EKSpan.ThisEvent, out errorCommit); } } NSError errorEvent; _eventStore.Commit(out errorEvent); } catch (Exception e) { //TODO : localisation await App.Instance.AlertService.ShowExceptionMessageAsync(e, "Impossible de renseigner votre calendrier iOS"); } }
/// <summary> /// Add new event to a calendar or update an existing event. /// Throws if Calendar ID is empty, calendar does not exist, or calendar is read-only. /// </summary> /// <param name="calendar">Destination calendar</param> /// <param name="calendarEvent">Event to add or update</param> /// <exception cref="System.ArgumentException">Calendar is not specified, does not exist on device, or is read-only</exception> /// <exception cref="System.UnauthorizedAccessException">Calendar access denied</exception> /// <exception cref="Calendars.Plugin.Abstractions.PlatformException">Unexpected platform-specific error</exception> public async Task AddOrUpdateEventAsync(Calendar calendar, CalendarEvent calendarEvent) { await RequestCalendarAccess().ConfigureAwait(false); EKCalendar deviceCalendar = null; if (string.IsNullOrEmpty(calendar.ExternalID)) { throw new ArgumentException("Missing calendar identifier", "calendar"); } else { deviceCalendar = _eventStore.GetCalendar(calendar.ExternalID); if (deviceCalendar == null) { throw new ArgumentException("Specified calendar not found on device"); } } EKEvent iosEvent = null; // If Event already corresponds to an existing EKEvent in the target // Calendar, then edit that instead of creating a new one. // if (!string.IsNullOrEmpty(calendarEvent.ExternalID)) { var existingEvent = _eventStore.EventFromIdentifier(calendarEvent.ExternalID); if (existingEvent.Calendar.CalendarIdentifier == deviceCalendar.CalendarIdentifier) { iosEvent = existingEvent; } } if (iosEvent == null) { iosEvent = EKEvent.FromStore(_eventStore); } iosEvent.Title = calendarEvent.Name; iosEvent.Notes = calendarEvent.Description; iosEvent.AllDay = calendarEvent.AllDay; iosEvent.Location = calendarEvent.Location ?? string.Empty; iosEvent.StartDate = calendarEvent.Start.ToNSDate(); // If set to AllDay and given an EndDate of 12am the next day, EventKit // assumes that the event consumes two full days. // (whereas WinPhone/Android consider that one day, and thus so do we) // iosEvent.EndDate = calendarEvent.AllDay ? calendarEvent.End.AddMilliseconds(-1).ToNSDate() : calendarEvent.End.ToNSDate(); iosEvent.Calendar = deviceCalendar; NSError error = null; if (!_eventStore.SaveEvent(iosEvent, EKSpan.ThisEvent, out error)) { // Without this, the eventStore will continue to return the "updated" // event even though the save failed! // (this obviously also resets any other changes, but since we own the eventStore // we can be pretty confident that won't be an issue) // _eventStore.Reset(); // Technically, probably any ekerrordomain error would be an ArgumentException? // - but we don't necessarily know *which* argument (at least not without the code) // - for now, just focusing on the start > end scenario and translating the rest to PlatformException. Can always add more later. if (error.Domain == _ekErrorDomain && error.Code == (int)EKErrorCode.DatesInverted) { throw new ArgumentException(error.LocalizedDescription, new NSErrorException(error)); } else { throw new PlatformException(error.LocalizedDescription, new NSErrorException(error)); } } calendarEvent.ExternalID = iosEvent.EventIdentifier; }
public async void AddEventToCalender(object sender, EventArgs e) { try { var store = new EKEventStore(); if (EKEventStore.GetAuthorizationStatus(EKEntityType.Reminder) == EKAuthorizationStatus.Authorized) { if (EKEventStore.GetAuthorizationStatus(EKEntityType.Event) == EKAuthorizationStatus.Authorized) { NSDate startDate = ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime)); NSDate endDate = ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventEndDate + " " + App.reminderEvent.eventEndTime)); NSPredicate query = store.PredicateForEvents(startDate, endDate, null); EKCalendarItem[] events = store.EventsMatching(query); bool exists = false; for (int i = 0; i < events.Length; i++) { if (events[i].Title == App.reminderEvent.eventName) { exists = true; } } if (!exists) { EKEvent eEvent = EKEvent.FromStore(store); eEvent.AddAlarm(EKAlarm.FromDate(ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime)))); eEvent.StartDate = startDate; eEvent.EndDate = endDate; eEvent.Title = App.reminderEvent.eventName; eEvent.TimeZone = new NSTimeZone("UTC"); eEvent.Location = App.reminderEvent.eventAddress; eEvent.Notes = App.reminderEvent.eventDescription; eEvent.Calendar = store.DefaultCalendarForNewEvents; NSError eventError; store.SaveEvent(eEvent, EKSpan.ThisEvent, out eventError); EKReminder reminder = EKReminder.Create(store); reminder.Title = App.reminderEvent.eventName; reminder.AddAlarm(EKAlarm.FromDate(ConvertDateTimeToNSDate(BaseFunctions.GetDateTimeFull(App.reminderEvent.eventStartDate + " " + App.reminderEvent.eventStartTime)))); reminder.TimeZone = new NSTimeZone("UTC"); reminder.Calendar = store.DefaultCalendarForNewEvents; await App.Current.MainPage.DisplayAlert("Alert", "This event is added to your calender", "Ok"); } else { await App.Current.MainPage.DisplayAlert("Alert", "This event is already added to your calender", "Ok"); } } else { store.RequestAccess(EKEntityType.Event, StoreAcceptRequest); } } else { store.RequestAccess(EKEntityType.Reminder, StoreAcceptRequest); } } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } }
private void AddCalendarEvent (object sender, System.EventArgs e) { EKEventStore store = new EKEventStore (); EKCalendar calendar = store.DefaultCalendarForNewEvents; NSError error = null; if (calendar != null) { EKEvent newEvent = EKEvent.FromStore (store); newEvent.Title = "Löwenbräukeller"; newEvent.Calendar = calendar; newEvent.StartDate = _reservation.ReservationTime; newEvent.EndDate = _reservation.ReservationTime.AddMinutes (30); newEvent.Availability = EKEventAvailability.Free; newEvent.Notes = _reservation.Advice; newEvent.Location = "Löwenbräukeller Gastronomie GmbH\n" + "Nymphenburgerstrasse 2\n" + "80335 München"; store.SaveEvent (newEvent, EKSpan.ThisEvent, out error); if (error == null) { var alert = new UIAlertView ( Locale.GetText ("Ihre Reservierung wurde in Ihrem Kalender eingetragen."), "", null, "OK", null); alert.Clicked += delegate { _lblAddCalendarEvent.Text = ""; _btnAddCalendarEvent.RemoveFromSuperview (); }; alert.Show (); } else { using (var alert = new UIAlertView (Locale.GetText("Error"),error.ToString(),null, "OK", null)) { alert.Show (); } } } }