Search This Blog

Monday 21 June 2021

How to add event phone calendar xamarin forms.

Xamarin Form Project 

ICalendarService Interface.

using System;
using System.Threading.Tasks;
 
namespace Test_App.Services.Interfaces
{
    public interface ICalendarService
    {
        Task<(bool isAdded, string message)> AddEventToCalendar(DateTime startDate, DateTime endDate, string title, string description, string location);
    }
}
 


Xamarin IOS Project

Create a CalendarService class that inherits ICalendarService Interface.

using EventKit;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Test_App.iOS.Services;
using Test_App.Services.Interfaces;
using UIKit;
 
[assembly: Xamarin.Forms.Dependency(typeof(CalendarService))]
namespace Test_App.iOS.Services
{
    public class CalendarService : ICalendarService
    {
        public async Task<(bool isAdded, string message)> AddEventToCalendar(DateTime startDate, DateTime endDate, string title, string description, string location)
        {
            bool isEventAdded = false;
            string message = string.Empty;
            try
            {
                var requestAccessResponse = await AppConstant.App.Current.EventStore.RequestAccessAsync(EKEntityType.Event);
 
                if (requestAccessResponse.Item1)
                {
                    NSDate nsStartDate = AppConstant.DateTimeToNSDate(startDate);
                    NSDate nsEndDate = AppConstant.DateTimeToNSDate(endDate);
                    NSPredicate query = AppConstant.App.Current.EventStore.PredicateForEvents(nsStartDate, nsEndDate, null);
 
                    EKEvent newEvent = EKEvent.FromStore(AppConstant.App.Current.EventStore);
                    var events = AppConstant.App.Current.EventStore.EventsMatching(query).ToList();
                    if (events?.Count > 0)
                    {
                        bool isExist = events.Any(f => f.Title == title && f.Notes == description && f.Location == location);
 
                        if (isExist)
                        {
                            message = "This Event already exist in your calendar.";
                            isEventAdded = true;
                        }
                    }
 
                    if (!isEventAdded)
                    {
                        newEvent.Calendar = AppConstant.App.Current.EventStore.DefaultCalendarForNewEvents;
                        newEvent.StartDate = nsStartDate;
                        newEvent.EndDate = nsEndDate;
                        newEvent.Title = title;
                        newEvent.Location = location;
                        newEvent.Url = new NSUrl("https://xamarincodingtutorial.blogspot.com/");
                        newEvent.Notes = description;
                        NSError et;
                        bool isSaved = AppConstant.App.Current.EventStore.SaveEvent(newEvent, EKSpan.ThisEvent, true, out et);
                        if (isSaved)
                        {
                            message = "Event Added to your calendar.";
                            isEventAdded = true;
                        }
                        else
                        {
                            if (et != null)
                            {
                                message = et.Description;
                            }
                        }
                    }
 
                }
                else
                {
                    message = "Calendar Permission required to save event";
                }
            }
            catch (Exception ex)
            {
                message = ex.Message;
            }
            return (isEventAdded, message);
        }
 
 
    }
}

Create a AppConstant.cs Class in your iOS Project that contain Date Conversion Code.

AppConstant.cs
using EventKit;
using Foundation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIKit;
 
namespace Test_App.iOS
{
    public static class AppConstant
    {
        public static NSDate DateTimeToNSDate(this DateTime date)
        {
            if (date.Kind == DateTimeKind.Unspecified)
                date = DateTime.SpecifyKind(date, DateTimeKind.Local);
            return (NSDate)date;
        }
 
        public class App
        {
            public static App Current
            {
                get { return current; }
            }
            private static App current;
            public EKEventStore EventStore
            {
                get { return eventStore; }
            }
            protected EKEventStore eventStore;
            static App()
            {
                current = new App();
            }
            protected App()
            {
                eventStore = new EKEventStore();
            }
        }
    }
}

Xamarin Android Project

Create a CalendarService class that inherits ICalendarService Interface.

using Android.Content;
using Android.Provider;
using System;
using System.Threading.Tasks;
using Test_App.Droid.Services;
using Test_App.Services.Interfaces;
 
[assembly: Xamarin.Forms.Dependency(typeof(CalendarService))]
namespace Test_App.Droid.Services
{
    public class CalendarService : ICalendarService
    {
        public async Task<(bool isAdded, string message)> AddEventToCalendar(DateTime startDate, DateTime endDate, string title, string description, string location)
        {
            bool isEventAdded = true;
            string message = string.Empty;
            try
            {
                Intent eventValues = new Intent(Intent.ActionInsert);
                eventValues.SetData(CalendarContract.Events.ContentUri);
                eventValues.AddFlags(ActivityFlags.NewTask);
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.CalendarId, 2);
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.Title, title);
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.Description, description);
                eventValues.PutExtra(CalendarContract.ExtraEventBeginTime, AppConstant.GetDateTimeMS(startDate.Year, startDate.Month, startDate.Day, startDate.Hour, startDate.Minute));
                eventValues.PutExtra(CalendarContract.ExtraEventEndTime, AppConstant.GetDateTimeMS(endDate.Year, endDate.Month, endDate.Day, endDate.Hour, endDate.Minute));
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventTimezone, "UTC");
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventEndTimezone, "UTC");
                eventValues.PutExtra(CalendarContract.Events.InterfaceConsts.EventLocation, location);
                Android.App.Application.Context.StartActivity(eventValues);
            }
            catch (Exception ex)
            {
                isEventAdded = false;
            }
            return (isEventAdded, message);
        }
    }
}

Create a AppConstant.cs Class in your Android Project that contain Date Conversion Code.

AppConstant.cs
using Java.Util;
 
namespace Test_App.Droid
{
    public static class AppConstant
    {
        public static long GetDateTimeMS(int year, int month, int day, int hr, int min)
        {
            Calendar c = Calendar.GetInstance(Java.Util.TimeZone.Default);
 
            c.Set(Java.Util.CalendarField.DayOfMonth, day);
            c.Set(Java.Util.CalendarField.HourOfDay, hr);
            c.Set(Java.Util.CalendarField.Minute, min);
            c.Set(Java.Util.CalendarField.Month, month -1);
            c.Set(Java.Util.CalendarField.Year, year);
 
            return c.TimeInMillis;
        }
    }
}

Implementations

 var eventDetails = await DependencyService.Get<ICalendarService>().AddEventToCalendar(startDateTime, endDateTime, eventName, description, location);


For Requesting Calendar Permission. (Android)

Plugin Used: Plugin.Permission.CrossPermission

var status = await CrossPermissions.Current.CheckPermissionStatusAsync<CalendarPermission>();
if (status != PermissionStatus.Granted)
{
	PermissionStatus permissionStatus = await CrossPermissions.Current.RequestPermissionAsync<CalendarPermission>();
	if (permissionStatus != PermissionStatus.Granted)
        {
              //"Heads Up! Please Allow Calendar Permission."
	}
}



5 comments:

  1. What is all those AppConstant stuff? Can you please share your code for the same?

    ReplyDelete
    Replies
    1. Hello Ron, I have updated the blog with AppConstant file

      Delete
  2. Im having the same issue with the AppConstant, "The name AppConstant does not exist in current context, any ideas of how to fix this?

    ReplyDelete

Popular Posts