Git Product home page Git Product logo

wmcmahan / react-native-calendar-events Goto Github PK

View Code? Open in Web Editor NEW
887.0 12.0 286.0 1.51 MB

πŸ“† React Native Module for iOS and Android Calendar Events

License: MIT License

Objective-C 38.57% JavaScript 6.78% Ruby 1.20% Java 52.99% Starlark 0.47%
android-calendar-events ios-calendar-events react-native calendar-events alarms calendar-api recurring-events ios-calendar-api android-calendar-api react-native-module andriod ios-library android-calendar ios-calendar ios-sdk andriod-sdk

react-native-calendar-events's Introduction

React Native Calendar Events

npm npm npm

A React Native module to help access and save events to iOS and Android calendars.

Getting started

This package assumes that you already have a React Native project or are familiar with React Native. If not, checkout the official documentation for more details about getting started with React Native.

Support

version react-native version
2.0.0+ 0.60.0+
pre 2.0.0+ 0.40.0+

For 0.59-, you should use jetify -r

Installation

$ npm install --save react-native-calendar-events
# --- or ---
$ yarn add react-native-calendar-events

Don't forget going into the ios directory to execute a pod install.

πŸ†˜ Manual linking

Because this package targets React Native 0.60.0+, you will probably don't need to link it manually. Otherwise if it's not the case, follow this additional instructions:

πŸ‘€ See manual linking instructions

iOS

Add this line to your ios/Podfile file, then run pod install.

target 'YourAwesomeProject' do
  # …
  pod 'RNCalendarEvents', :path => '../node_modules/react-native-calendar-events'
end

Android

1 - Add the following lines to android/settings.gradle:

include ':react-native-calendar-events'
project(':react-native-calendar-events').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-calendar-events/android')

2 - Add the implementation line to the dependencies in android/app/build.gradle:

dependencies {
  // ...
  implementation project(':react-native-calendar-events')
}

3 - Add the import and link the package in MainApplication.java:

import com.calendarevents.RNCalendarEventsPackage; // <- add the RNCalendarEventsPackage import

public class MainApplication extends Application implements ReactApplication {

  // …

  @Override
  protected List<ReactPackage> getPackages() {
    @SuppressWarnings("UnnecessaryLocalVariable")
    List<ReactPackage> packages = new PackageList(this).getPackages();
    // …
    packages.add(new RNCalendarEventsPackage());
    return packages;
  }

  // …
}

iOS specific instructions

Add RNCalendarEvents, as well as EventKit.framework to project libraries if not already done.

Setting up privacy usage descriptions may also be required depending on which iOS version is supported. This involves updating the Property List, Info.plist, with the corresponding key for the EKEventStore api. Info.plist reference.

For updating the Info.plist key/value via XCode, add a Privacy - Calendars Usage Description key with a usage description as the value. Resulting change to Info.plist should look something like:

<key>NSCalendarsUsageDescription</key>
<string>This app requires access to the calendar</string>

API

The following API allows for interacting with both iOS and Android device calendars. See the full list of available event fields.

import RNCalendarEvents from "react-native-calendar-events";

checkPermissions

Get calendar authorization status. You may check for the default read/write access with no argument, or read-only access on Android by passing boolean true. iOS is always read/write.

RNCalendarEvents.checkPermissions((readOnly = false));

Returns: Promise

  • fulfilled: String - denied, restricted, authorized or undetermined
  • rejected: Error

requestPermissions

Request calendar authorization. Authorization must be granted before accessing calendar events.

RNCalendarEvents.requestPermissions((readOnly = false));

(readOnly is for Android only, see below)

Android note: this is necessary for targeted SDK of >=23. iOS note: This method will crash, if you didn't update Info.plist. Follow carefully installation instruction.

Returns: Promise

  • fulfilled: String - denied, restricted, authorized or undetermined
  • rejected: Error

Read-Only requestPermissions (Android only)

⚠️ Note that to restrict to read-only usage on Android (iOS is always read/write) you will need to alter the included Android permissions as the AndroidManifest.xml is merged during the Android build.

You do that by altering your AndroidManifest.xml to "remove" the WRITE_CALENDAR permission with an entry like so:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  >
  <!-- ... -->
  <uses-permission tools:node="remove" android:name="android.permission.WRITE_CALENDAR" />

findCalendars

Finds all the calendars on the device.

RNCalendarEvents.findCalendars();

Returns: Promise

  • fulfilled: Array - A list of known calendars on the device
  • rejected: Error

saveCalendar

Create a calendar.

RNCalendarEvents.saveCalendar(calendar);

⚠️ When you want to save a calendar, you need to use a valid source (find using findCalendars).

Arguments:

  • calendar: Object - Calendar to create.

Returns: Promise

  • fulfilled: The id of the created calendar
  • rejected: Error

removeCalendar

Removes a calendar.

RNCalendarEvents.removeCalendar(id);

Arguments:

  • id: String - The id of the calendar to remove.

Returns: Promise

  • fulfilled: Bool - Successful
  • rejected: Error

findEventById

Find calendar event by id. Returns a promise with fulfilled found events.

RNCalendarEvents.findEventById(id);

Arguments:

  • id: String - The events unique id.

Returns: Promise

  • fulfilled: Object | null - Found event with unique id.
  • rejected: Error

fetchAllEvents

Fetch all calendar events. Returns a promise with fulfilled found events.

RNCalendarEvents.fetchAllEvents(startDate, endDate, calendars);

Arguments:

  • startDate: String - The start date of the range of events fetched.
  • endDate: String - The end date of the range of events fetched.
  • calendars: Array - List of calendar id strings to specify calendar events. Defaults to all calendars if empty.

Returns: Promise

  • fulfilled: Array - Matched events within the specified date range.
  • rejected: Error

saveEvent

Creates or updates a calendar event. - wiki guide

RNCalendarEvents.saveEvent(title, details, options);

Arguments:

  • title: String - The title of the event.
  • details: Object - The event's details.
  • options: Object - Options specific to the saved event. Note that on Android, saveEvent accepts an additional option sync (boolean) to prevent syncing issues.

Returns: Promise

  • fulfilled: String - Created event's ID.
  • rejected: Error

To update an event, the event id must be defined. - wiki guide

RNCalendarEvents.saveEvent(title, {
  id: "FE6B128F-C0D8-4FB8-8FC6-D1D6BA015CDE",
});

Example for saveEvent

Creating events is fairly straightforward. Hopefully the following explanation can help.

Basic saveEvent

For both iOS and Android the pattern is simple; the event needs a title as well as a startDate and endDate. The endDate should also be a date later than the startDate.

RNCalendarEvents.saveEvent('Title of event', {
  startDate: '2016-08-19T19:26:00.000Z',
  endDate: '2017-08-19T19:26:00.000Z'
}) 
Specify a calendar saveEvent

The example above will simply save the event to your devices default calendar. If you wish to control which calendar the event is saved to, you must provide the calendarId. This will ensure your event is saved to an expected calendar.

RNCalendarEvents.saveEvent('Title of event', {
  calendarId: '141',
  startDate: '2016-08-19T19:26:00.000Z',
  endDate: '2017-08-19T19:26:00.000Z'
}) 
Additional fields with saveEvent

There are also other writable fields available. For example, you may wish to specify the location of the event or add additional notes for the event. Complete list of fields can be found in the wiki.

RNCalendarEvents.saveEvent('Title of event', {
  calendarId: '141',
  startDate: '2016-08-19T19:26:00.000Z',
  endDate: '2017-08-19T19:26:00.000Z',
  location: 'Los Angeles, CA',
  notes: 'Bring sunglasses'
}) 

removeEvent

Removes calendar event.

RNCalendarEvents.removeEvent(id, options);

Arguments:

  • id: String - The id of the event to remove.
  • options: Object - Options specific to event removal.

Returns: Promise

  • fulfilled: Bool - Successful
  • rejected: Error

Event fields

Property Type Description iOS Android
id* String Unique id for the calendar event. βœ“ βœ“
calendarId** String Unique id for the calendar where the event will be saved. Defaults to the device's default calendar. βœ“ βœ“
title String The title for the calendar event. βœ“ βœ“
startDate String The start date of the calendar event in ISO format. βœ“ βœ“
endDate String The end date of the calendar event in ISO format. βœ“ βœ“
allDay Bool Indicates whether the event is an all-day
event. βœ“ βœ“
recurrence String The simple recurrence frequency of the calendar event daily, weekly, monthly, yearly or none. βœ“ βœ“
recurrenceRule ** Object The events recurrence settings. βœ“ βœ“
occurrenceDate* String The original occurrence date of an event if it is part of a recurring series. βœ“
isDetached Bool Indicates whether an event is a detached instance of a repeating event. βœ“
url String The url associated with the calendar event. βœ“
location String The location associated with the calendar event. βœ“ βœ“
structuredLocation String The structuredLocation associated with the calendar event. βœ“
notes String The notes associated with the calendar event. βœ“
description String The description associated with the calendar event. βœ“
alarms Array The alarms associated with the calendar event, as an array of alarm objects. βœ“ βœ“
attendees* Array The attendees of the event, including the organizer. βœ“ βœ“
calendar* Object The calendar containing the event. βœ“ βœ“
skipAndroidTimezone Bool Skip the process of setting automatic timezone on android βœ“
timeZone String The time zone associated with the event βœ“

Calendar

Property Type Description iOS Android
id String Unique calendar ID. βœ“ βœ“
title String The calendar’s title. βœ“ βœ“
type String The calendar’s type. βœ“ βœ“
source String The source object representing the account to which this calendar belongs. βœ“ βœ“
isPrimary* Bool Indicates if the calendar is assigned as primary. βœ“ βœ“
allowsModifications* Bool Indicates if the calendar allows events to be written, edited or removed. βœ“ βœ“
color* String The color assigned to the calendar represented as a hex value. βœ“ βœ“
allowedAvailabilities* Array The event availability settings supported by the calendar. βœ“ βœ“

Attendees

Property Type Description iOS Android
name String The name of the attendee. βœ“ βœ“
email* String The email address of the attendee. βœ“ βœ“
phone* String The phone number of the attendee. βœ“

Recurrence rule

Property Type Description iOS Android
frequency String Event recurring frequency. Allowed values are daily, weekly, monthly, yearly. βœ“ βœ“
endDate String Event recurring end date. This overrides occurrence. βœ“ βœ“
occurrence Number Number of event occurrences. βœ“ βœ“
interval Number The interval between events of this recurrence. βœ“ βœ“

Alarms

Property Type Description iOS Android
date String or Number If a String is given, an alarm will be set with an absolute date. If a Number is given, an alarm will be set with a relative offset (in minutes) from the start date. βœ“ βœ“
structuredLocation Object The location to trigger an alarm. βœ“

Alarm structuredLocation

Property Type Description iOS Android
title String The title of the location. βœ“
proximity String A value indicating how a location-based alarm is triggered. Possible values: enter, leave, none. βœ“
radius Number A minimum distance from the core location that would trigger the calendar event's alarm. βœ“
coords Object The geolocation coordinates, as an object with latitude and longitude properties βœ“

Options

Property Type Description iOS Android
exceptionDate String The start date of a recurring event's exception instance. Used for updating single event in a recurring series βœ“ βœ“
futureEvents Bool If true the update will span all future events. If false it only update the single instance. βœ“

Calendar options

Property Type Description iOS Android
title String The calendar title (required) βœ“ βœ“
color String The calendar color (required) βœ“ βœ“
entityType String 'event' or 'reminder' (required) βœ“
name String The calendar name (required) βœ“
accessLevel String Defines how the event shows up for others when the calendar is shared doc(required) 'contributor', 'editor', 'freebusy', 'override', 'owner', 'read', 'respond', 'root' βœ“
ownerAccount String The owner account for this calendar, based on the calendar feed doc(required) βœ“
source Object The calendar Account source (required) βœ“
source.name String The Account name (required) βœ“
source.type String The Account type βœ“
source.isLocalAccount Bool The source (required if source.type is not used) βœ“

* Read only, ** _Write only

Troubleshooting

These are some common issues you may run into while using react-native-calendar-events library. If you encounter something that is not listed here, try searching in GitHub issues of react-native-calendar-events.

After saving an event, it disappear form the calendar

This might be related to a sync issue. You need to be sure that the event you saved is matching what your device will keep in sync.

For iOS, you might have not all event synced. You might need to update this iOS settings in Settings > Calendar > Sync > All Events. If that's not enough, it might be worth checking iOS iCloud sync documentation.
For Android, you can have a look to Google Calendar sync problems documentation.

Duplicated events after editing and saving an event

Another symptom of syncing issue. See the issue above. Note that on Android, saveEvent accepts an additional option sync (boolean) to prevent syncing issues.

Wiki

Authors

See also the list of contributors who participated in this project.

License

This project is licensed under the MIT License - see the LICENSE.md file for details

Acknowledgments

Big thanks to all who have contributed, raised an issue or simply find use in this project. Cheers!

react-native-calendar-events's People

Contributors

aarkalyk avatar akandaurov avatar alimek avatar chiformihai avatar davidgruebl avatar dependabot[bot] avatar dozoisch avatar dstop75 avatar eleddie avatar franleplant avatar hariks789 avatar hugofelp avatar jedrichards avatar jenniferburch avatar joeybenenati avatar jpaas avatar krizpoon avatar lilach avatar lorienhw avatar migue1s avatar mikehardy avatar mikeumus avatar moox avatar nati-lara avatar osterbergmarcus avatar saghul avatar steven-sh avatar trevorah avatar wmcmahan avatar yzlin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-calendar-events's Issues

Add autoformatting for dates

Hey all. Really useful library, and I've loved it so far.

One thing I've found that was a little annoying at first was having to format the start and end date strings when saving an event. I've made a decision to avoid moment.js as I really don't do a lot of work with dates in my app, and I didn't want the extra code size. I also found out the hard way that react-native-calendar-events requires strings for start and end because there was an NPE when I supplied a Date for start and end.

I ended up having to write a custom formatter for this, and it looks like you guys parse this string into a native Date object afterward anyway. I would love to supply a javascript Date object or even an epoch long to represent dates for saveEvent

List possible calendars to export too

I think this is more of a feature request, but I would love the ability to select the calendar to save my calendar events to. I hope to have more time to possibly contribute to this repo, but something I would like to see in the next version or so! You guys rock though and thanks for the library!

Error on Android after call to saveDate

I commented on #23, but I'm seeing a native error when trying to make a call to RNCalendarEvents.saveEvent on Android. cc @lilach

Here's the stack trace, although it probably isn't very insightful.

Error: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
    at createErrorFromErrorData (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7099:11)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7062:35
    at MessageQueue.__invokeCallback (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7442:10)
    at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7294:8
    at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7213:1)
    at MessageQueue.invokeCallbackAndReturnFlushedQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7293:1)
    at onmessage (http://localhost:8081/debuggerWorker.js:44:56)

allDay error on Android

Hi,

Getting an error on Android when setting allDay: false. The event is getting created but on the emulator the app quits, on the device the app doesn't quit but the error stacktrace is the same.

Android Genymotion emulator (Android 7.0) / Device OnePlus (Android 6.0.1)
RN 0.44.0
Calendar-Events 1.3.6

error stacktrace from android studio:

05-18 11:57:13.411 21570-21580/? E/ContentValues: Cannot cast value for allDay to a Integer: false
                                                  java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
                                                      at android.content.ContentValues.getAsInteger(ContentValues.java:288)
                                                      at com.android.providers.calendar.CalendarProvider2.fixAllDayTime(CalendarProvider2.java:1530)
                                                      at com.android.providers.calendar.CalendarProvider2.insertInTransaction(CalendarProvider2.java:2192)
                                                      at com.android.providers.calendar.SQLiteContentProvider.insert(SQLiteContentProvider.java:99)
                                                      at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                      at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                      at android.os.Binder.execTransact(Binder.java:453)
05-18 11:57:13.412 21570-21580/? E/ContentValues: Cannot cast value for allDay to a Integer: false
                                                  java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
                                                      at android.content.ContentValues.getAsInteger(ContentValues.java:288)
                                                      at com.android.providers.calendar.CalendarProvider2.updateEventRawTimesLocked(CalendarProvider2.java:3024)
                                                      at com.android.providers.calendar.CalendarProvider2.insertInTransaction(CalendarProvider2.java:2202)
                                                      at com.android.providers.calendar.SQLiteContentProvider.insert(SQLiteContentProvider.java:99)
                                                      at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                      at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                      at android.os.Binder.execTransact(Binder.java:453)
05-18 11:57:13.413 21570-21580/? E/ContentValues: Cannot cast value for allDay to a Integer: false
                                                  java.lang.ClassCastException: java.lang.Boolean cannot be cast to java.lang.Number
                                                      at android.content.ContentValues.getAsInteger(ContentValues.java:288)
                                                      at com.android.providers.calendar.CalendarInstancesHelper.updateInstancesLocked(CalendarInstancesHelper.java:698)
                                                      at com.android.providers.calendar.CalendarProvider2.insertInTransaction(CalendarProvider2.java:2203)
                                                      at com.android.providers.calendar.SQLiteContentProvider.insert(SQLiteContentProvider.java:99)
                                                      at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
                                                      at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
                                                      at android.os.Binder.execTransact(Binder.java:453)

fetchAll and recurring events in Android

Hi! Thanks a lot for your library.

I've double checked this behavior in at least two android devices.

Expected: fetchAll should fetch all events in all calendars
Actual: fetchAll is not fetching the recurrent events in all calendars

It fetches correctly all events but recurring ones.

Is there something am I missing or is this an actual bug?

Thanks a lot!
Fran

[Proposals] iOS 8.2 crashes on fetchAllEvents

Description

Got BAD_ACCESS exception on iOS 8 when invoking fetchAllEvents

#0	0x00000001006cb684 in -[RNCalendarEvents serializeCalendarEvents:] at RNCalendarEvents.m:331
NSDictionary *emptyCalendarEvent = @{
    _title: @"",
    _location: @"",
    _startDate: @"",
    _endDate: @"",
    _allDay: @NO,
    _notes: @"",
    _url: @"",
    _alarms: @[],                 <- Thread 1: EXC_BAD_ACCESS (code = 1, address=0x0)
    _recurrence: @""
};

Solution

Change NSArray literal notation into [NSArray array] fixes this. I don't know why this happens because array literals notation is supported since Apple LLVM 4.0.

NSDictionary *emptyCalendarEvent = @{
    _title: @"",
    _location: @"",
    _startDate: @"",
    _endDate: @"",
    _allDay: @NO,
    _notes: @"",
    _url: @"",
-   _alarms: @[],
+   _alarms: [NSArray array],
    _recurrence: @""
};

Additional Information

React Native version: 0.39.0
Platform: iOS 8.2 (12D508)
Operating System: MacOS 10.12 (16C67)

Is that possible to saveEvent not as a birthday in Android default calendar?

"react-native-calendar-events": "1.3.6"
"react-native": "0.41.2"

I'm using Android 6.0.1 device and this code

 RNCalendarEvents.findCalendars().then(calendars => {// handle calendars});

returns Array with Objects structured:

[{
  allowsModifications:false,
  id:"1",
  isPrimary:false,
  source:"[email protected]",
  title:"Contacts",
},{
  allowsModifications:false,
  id:"2",
  isPrimary:false,
  source:"[email protected]",
  title:"Holidays in Ukraine"
},...]

If I write calendarId (I tried all id's) when save event my app shutting down and not save event.
If I not write it, the event appears as birthday (like in #54)
Code that saves events:

RNCalendarEvents.saveEvent(`title`, {
  location: `location`,
  notes: `location`,
  startDate: ISOFormattedDate,
  endDate: ISOFormattedDate
}).then(res=>console.log(res)).catch(error => {
  console.log(error);
});

in IOS works well. Any suggestions about how to save event not as birthday in default calendar?
Also this events dissapears from default calendar after some time.

"No Calendar has been set" after authorization until App is restarted

I'm on iOS and in my app I authorize the calendar store, but I cannot set events until I restart the app. It still acts like the calendar system has not been authorized when I try to add events directly after authorization. Is there some way I'm supposed to reinitialize the calendar object so that it can properly see the new settings?

Cheers

Google Cal & Exchange

Hello

First, thanks for building such a react-native code and share it.

Will it find calendars and thus events of Google Calendar and MS Exchange calendar if the device has them configured?

Cheers!

Unable to delete calendar in Android (with fix)

Hi,

I was receiving an error when deleting an event in Android using the removeEvent() call.

I fixed it by passing null instead of selection in the second param to cr.delete, in CalendarEvents.java:

Old

        String selection = "((" + CalendarContract.Events.DELETED + " != 1))";
        int rows = cr.delete(uri, selection, null);

Fixed

        int rows = cr.delete(uri, null, null);

Please review to include in a later release. I found this solution by googling - I am not an expert on Android calendars.

Error getting default calendar for new events

Hi,
I'm getting this error:

Error getting default calendar for new events: Error Domain=EKCADErrorDomain Code=1013 "(null)"
2017-03-10 17:58:17.542 [info][tid:com.facebook.react.JavaScript] errorError: No calendar has been set.

Already linked the libraries on XCode.

Can I solve this problem ?
Thanks.

[iOS] Working in debug but error when deployed (hockey app)

Hello,

I'm having a little issue hard to debug.

React native calendar events works quite well on my dev env but once the app deployed through hockey app, the add to calendar does not work on iOS and leaves me with an error.

Find below a screenshot of the error:
img_8311

Like that for the moment I did not find a way to be able to reproduce this error and access it on my dev env, so I'm looking for your help.

Would you have any idea why this happens ?

Thanks,

Xavier

RNCalendarEvents is undefined

Using React-Native v0.33.0

After running import RNCalendarEvents from 'react-native-calendar-events';, RNCalendarEvents is undefined.

Unable to require with NodeJS testing

When trying to run a test I receive the Error:

"Cannot find module 'react-native-calendar-events'"

I believe the reason for this error is there is no main file specified in package.json and the normal require resolver does not know how to handle index.ios.js vs index.android.js.

removeEvent throws Exception

When calling RNCalendarEvents.removeEvent('F7A090EC-115E-4AD2-BD6E-439936FC2C75') I get this error:

Exception '*** -[__NSPlaceholderDictionary initWithObjects:forKeys:count:]: attempt to insert nil object from objects[0]' was thrown while invoking removeEvent on target RNCalendarEvents with params (
    "F7A090EC-115E-4AD2-BD6E-439936FC2C75"
)

Any thoughts?

npm install

In the readme, it says we need
npm install react-native-calendar-events
to install the library, in fact we need to say
npm install react-native-calendar-events --save
I am new to react native, and this costs me some time to figure it out. Can you update ReadMe so that it won't confuse other people

saveEvent returning id 0

Hi,

This is my addCalendarEvent function

  addCalendarEvent(){
    console.log("add Calendar Event");

    RNCalendarEvents.authorizeEventStore()
      .then(status => {
        console.log(status);
      })
      .catch(error => {
       console.log(error);
      });

    RNCalendarEvents.authorizationStatus()
      .then(status => {
        //status = denied, restricted, authorized or undetermined
        console.log("Calendar authorizationStatus:", status);
      })
      .catch(error => {
        console.log("Calendar authorizationError:", error);
      });


      startDate = new Date("13 Jan 2017, 02:02 AM");
      endDate = new Date(Date.parse(startDate) + 3600000);

      RNCalendarEvents.saveEvent('test', {
        location: 'location',
        notes: 'notes',
        description: 'notes',
        startDate: startDate.toISOString(),
        endDate: endDate.toISOString(),
        allDay: false,
        recurrence: 'none',
        alarms: [{
          date: -30 // or absolute date - iOS Only
        }]
      })
      .then(id => {
        console.log("Calendar event id:", id);
      })
      .catch(error => {
          console.log("Calendar add event error:", error);
      });


      startDate = '2017-01-12T00:00:00.000Z',
      endDate = '2017-01-13T23:59:59.000Z',

      RNCalendarEvents.fetchAllEvents(startDate, endDate)
      .then(events => {
        console.log("events found", events);
      })
      .catch(error => {
       console.log("error finding events", error)
      });

  }

In the console I get the following results:

screen shot 2017-01-13 at 1 34 10 am

As you can see the event id is 0 from the saveEvent Promise and no event is added as can be seen from the fetchAllEvents result also.

Can someone help me understand what's going wrong?

RN 0.39.2
Testing on Android 6 device

Fetch event by ID

Hello I was wondering if there are any plans to add a method to fetch an event by its ID. I have a use case where I want to be able to query an event to see if it exists by the ID as I won't know if the current date stored on my device is correct and can't use it in the fetch-all-in-date-range method. My app will have support for multiple devices, offline mode, and synching via webserver, so I'm interested in being able to check if a single event is already set up on the device, and if so, does the date in iOS calendar match what is stored in my App's databse.

I see that there is a method in the Calendar API for this

https://developer.apple.com/reference/eventkit/ekeventstore/1507490-event

I'd take a whack at it myself but I zero experience in that language.

For now I can do a fetchAll using a huge daterange and then loop through every event to see if the iOS event that I'm looking for exists and then whether it's set for the correct date.

Cheers and thanks for putting this package together

Event not being emitted

I have setup the application and followed, and double checked every step.
When hitting the button to add an event, nothing happens, no calendar, no event, no error, nothing.

function checkPermissions(event, reminder) {
  RNCalendarEvents.authorizeEventStore(({status}) => {
    if(status.toLowerCase() === 'authorized') {
      return _addToCalendar(event, reminder);
    }

    return AlertIOS.alert(
     'Unable to create event',
     'We need permissiont o access your calendar in order to create an event.'
    );
  });
}

function _addToCalendar(event, reminder) {
  const calDate = reminder ? moment(event.sortDate).subtract(1, 'month') : event.sortDate;
  const reminderDate = moment(calDate).hour(8).minute(0).toISOString();
  const eventDate = moment(calDate).hour(0).minute(0).toISOString();

  if(reminder) {
    RNCalendarEvents.saveEvent(`Reminder: enter ${event.title}`, {
      location: 'location',
      notes: 'notes',
      startDate: reminderDate,
      endDate: reminderDate,
    });
  } else {
    RNCalendarEvents.saveEvent('title', {
      location: event.location,
      notes: 'notes',
      startDate: eventDate,
      endDate: eventDate,
      alarms: [{
        date: -60
      }]
    });
  }
}

What have I missed that makes this work.

Thanks

Error: No calendar has been set.

Hey all,
I am trying to add events to the user calendar via my React Native app.
But I am getting an error saying No calendar has been set after calling RNCalendarEvents.saveEvent (), and when trying to request calendar authorization with RNCalendarEvents.authorizeEventStore()
my app crashes.

Regards,
Mehdi

Getting authorization to Calender(question)

Sorry if this a naive question, First time developing react-native app. In android I would normally declare permission required in manifest, <uses-permission android:name="android.permission.READ_CALENDAR" />, So even with this I would still need to use authorizeEventStore to get secondary permission?, or is it only necessary if the user denied it initially and at run time you want to offer them to change their mind?

addListener of undefined on NativeAppEventEmitter

const {NativeAppEventEmitter} = React;

       this.eventEmitter = NativeAppEventEmitter.addListener('calendarEventsChanged', () => {
          RNCalendarEvents.saveEvent(this.props.data.post_title, {
            location: `PVJ ${this.props.data.custom_fields.tenant.post_title}`,
            notes: 'notes',
            startDate: date.format("YYYY-MM-DDTHH:mm:ss.sssZ"),
            endDate: date.format("YYYY-MM-DDTHH:mm:ss.sssZ")
          }, events => {
            console.log("RNCalendarEvents saveEvent:", events)
          });
        });

i keep getting error "addListener of undefined", did i do wrong?

fectchAll doesn't return all events

On my macbookpro I have my calendars setup to sync to a remote caldav server, and I can see a whole list of full year's events on the calendar upon successfully setup. And then I wrote the following code in my react-native dev project:

    componentDidMount() {
      RNCalendarEvents.fetchAllEvents('2016-01-01T00:00:00.000Z', 
                                      '2016-12-30T23:00:00.000Z', 
                                      events => {
                                        console.log(events)
                                      }
                                    )
    }

But I only see 4 items which are synced with my friends birthday found in the email. Is there anyway I can do with this issue?

failed to install

hi, i'm quite new on installing nativeModules, so could you please explain this section
"Then add RNCalendarEvents, as well as EventKit.framework to project libraries.

For iOS 8 compatibility, you may need to link your project with CoreFoundation.framework (status = Optional) under Link Binary With Libraries on the Build Phases page of your project settings."

into a steps?

Thank You

[Android] Multiple "allday events"

Hey, I have a problem with the allday attributes.
If I save an event from Monday 0:00 to Tuesday 23:59 with the "allday" attribute, the event is only registered for Monday. Tuesday is ignored -this works well on IOS-.

I don't know if it's the way android calendar works but if I remove the allday attribute on my default HTC calendar the Monday event is automatically flagged "allday" and the Tuesday is filled from 0:00 to 23:59.

Now if I create an event from Monday 0:00 to Wednesday 0:00 without "allday" attribute i've got my Monday and Tuesday flagged as "allday" event.

Anyone knows if it's the right way to save "allday" events on android ? or my htc default calendar is pretty clever and this would fail on all other android devices ?

anyway, thanks for the good work.

How to save multiple events?

For single event, I save to device without any problems.
But when I try to save many events in the array, it fails.
console complains: TypeError: Cannot read property 'alert' of undefined
Here is my Code:

saveCalendar() {
       console.log('RAC', this.props.eventops);
       const myCalendar = this.props.eventops;
       myCalendar.forEach(cal => {
           //console.log('THE CAL', cal);
        let evtDate = new Date(cal.EventDate);
            evtDate = evtDate.toISOString();
             console.log('THE CAL', evtDate);

       let evtEndDate = new Date(cal.EventEndDate);
       evtEndDate = evtEndDate.toISOString();
         console.log('THE CAL', evtEndDate);
          
           RNCalendarEvents.saveEvent(`Abu Dhabi - ${cal.Title}`, {
               location: `${cal.Location}`,
               notes: `${cal.Text}`,
               startDate: `${evtDate}`,
               endDate: `${evtEndDate}`
           })
           .then(id => {
               AlertIOS.alert('Announcement', 'Add the event Successfully!', console.log(id));
           })
           .catch(error => {
           console.log(error);
       }, setTimeout(() => {
           this.popupDialog.closeDialog();
       }, 50));
       });
   }

Alert to notify user that the event has been added

Hi, thank you for the component.
Is there a way to show the user an alert modal confirming that the event has been added successfully to the calendar? And also a modal to say to the user, "Do you want to see the event added in the the caledar?" Yes/No

Thank you in advance

Fatal Exception on event adding

My application stop working when I try to add new event into calendar.

Here call example:

RNCalendarEvents.saveEvent('Test', { 
	location: 'New York, United States',
	startTime: '2017-03-29T10:30:00.000Z',
	endTime: '2017-03-29T11:30:00.000Z',
	description: 'Test description' 
});

Here the exception description from logcat:

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.net.Uri.getLastPathSegment()' on a null object reference
    at com.calendarevents.CalendarEvents.addEvent(CalendarEvents.java:308)
    at com.calendarevents.CalendarEvents$2.run(CalendarEvents.java:510)
    at java.lang.Thread.run(Thread.java:818)

Library version: 1.3.6
React Native: 0.42

Undefined is not an object

Hi,
I have been trying for a while to get this module to work in React Native and every time I run
RNCalendarEvents.authorizationStatus() .then(status => { // handle status }) .catch(error => { // handle error });

I get the error that 'undefined is not an object'

NativeModules.CalendarEvents return "undefined".

For me in Android CalendarEvents.java didn't added to Native Modules. So var CalendarEvents = NativeModules.CalendarEvents call in React library returns undefined.
Set up properly.
Version:
react-native-cli: 2.0.1
react-native: 0.41.2

ios(sim) - Application closes when executing RNCalendarEvents.authorizeEventsStore()

Hi
I'm using a simulator running iOS 10.2 (iPhone6). When RNCalendarEvents.authorizeEventsStore() is run the application closes and produces no errors.. when i check authorized status is shows as undetermined.
using the code from the readme

RNCalendarEvents.authorizeEventStore()
.then(status => {
// handle status
})
.catch(error => {
// handle error
});

remove repeating event

Hi! I've found that it's impossible to remove event with recurrence.
Also, I can't update recurrence status to none for existing event (the second one maybe is not an issue, I've just tried to hack someway to remove existing recurrence events);

Crashes without CoreFoundation.framework in iOS8

After installing this module, the app compiles fine but crashes instantly using the iOS 8.2 simulator (anything less than iOS9, I believe, and before loading RN) unless CoreFoundation.framework is linked with Optional status. Due to an unhelpful error message, it took a lengthy git bisect to track down sometime after the fact, so it seemsβ€”unless this is symptomatic of some other issueβ€”that CoreFoundation.framework (Status: Optional) could perhaps be included in the installation instructions. Unless, of course, there's a more effective/correct solution.

Error message:

dyld: Symbol not found: ___NSArray0__
  Referenced from: /Users/rreusser/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/.../MyApp.app/MyApp
  Expected in: /Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 8.2.simruntime/Contents/Resources/RuntimeRoot/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation
 in /Users/rreusser/Library/Developer/CoreSimulator/Devices/.../data/Containers/Bundle/Application/.../MyApp.app/MyApp

cannot set when recurring event ends

RNCalendarEvents.saveEvent('title', { location: 'location', notes: 'notes', startDate: '2017-05-20T19:26:00.000Z', endDate: '2017-05-20T20:26:00.000Z', alarms: [{ date: -1 // or absolute date - iOS Only }], recurrence: 'daily' })
This will create a recurring event from 19:26 to 20:26 daily. And it goes on forever.
In your RNCalendarEvent.m, you set the end date to be nil,
if ([validFrequencyTypes containsObject:frequency]) { rule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:[self frequencyMatchingName:frequency] interval:1 end:nil]; }
which means the recurring event goes on forever.
Can you update this part to allow user to set an end date.

iOS simulator alert not working

Hi,

Got the code to write an event in the calendar and the calendar event does show an alert of 30 min before but I did not get any alert message. Am I missing something? On Android device the same code gives a nice alert notification.
My first time dabbling with iOS so don't know if this is how it is in simulator.

RN 0.40.0
iPhone6 iOS 10.1

FindCalendars not listing calendars on iOS

Hi,

On Android I can list all my device calendars, even the "Contacts" calendar. But on iOS the FindCalendars returns an empty array. I tried on different iOS devices configured with iCloud and Google calendars but the list is always empty.

My code:

   RNCalendarEvents.authorizationStatus()
      .then(status => {

        RNCalendarEvents.findCalendars()
          .then(calendars => {
            console.log('CALENDARS:', calendars);
            this.setState({
              calendars,
            });
            if (calendars.length > 0){
              this._selectCalendar(calendars);
            } else {
              Alert.alert(this.props.title, 'No calendars defined.')
            } 
          })
          .catch(error => {
            console.log('ERROR!', error);
          });

      })
      .catch(error => {
        console.log('ERROR!', error);
      });

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.