Beginner's Guide to Swift EventKit-request Permissions

Source: Internet
Author: User

Beginner's Guide to Swift EventKit-request Permissions

EventKit provides a series of classes for getting and Operating User calendar events and reminders. in the following tutorial, my goal is to lead you out of the first step of using EventKit to build an application. my goal is to take the first step in building an application using EventKit. I will demonstrate how to request a permission from a user's calendar. I will also show several examples of handling user responses (when they grant access permissions or deny ).

Example scenario

Scenario

Let's first propose a basic solution as an example of this tutorial.

Suppose we are building an application, and now there is a single view controller. We want this view controller to display the calendar list if user authorization permits. If the user rejects access, we will display a message to the user, indicating that our application cannot run when there is no access, we will also allow them to set authorized access in their device settings by clicking a button.

I have created an application as an example-jump to GitHub to view and study the code of this example.

Resources

Xcode engineering example

Storyboard setup

Set the story panel

The first step to use EventKit is to create a user interface for yourself to handle the issue. When your first program is started, the user will "Can this program access your calendar ?" For different responses, we will soon get details on how to request this license. but first, let's analyze how we can arrange our storyboards by using some views that make correct operations for a given response caused by a license operation.

Users can grant access permissions, or refuse to grant access permissions to notify their calendar or reminders. We need to prepare for these two cases.

When an access permission is granted, tableview displays the calendar list.

I am optimistic today, so let's start with the situation where users have granted us access to their calendar from the very beginning.

When a user grants us access permissions, we want to list the calendar of a table view. in the next tutorial, We will worry about data source settings. now, we will drag a table view from the toolbar.

I have done a few things to get the table view that fills up the entire screen. generally, when you drag a table view from the toolbar, it fills up the entire scenario in the story board. in the layout, I drag down the top edge to know that it "captures" the row that is located at the bottom of the desired status bar. then, I set the following limits:

Center X

Center Y

Equal width to Superview

Top space to Top Layout Guide for height.

I have created a short screenshot for setting the table view. For a complete exercise, see the following link:

Resources

Resources

Screencast: Setting Up a Table View

Full transcript

The detailed view of these constraints and the visual effect of the storyboard looks like a table-mounted view.

Finally, in the story board, I have set the hidden attribute of this table view to true. after the user permits or denies access to the calendar, I will switch the visibility of the table, but I think it is worth noting that in my example, the initial status of the table view is hidden.

"License required" view when access is denied

But sometimes, users refuse to authorize access to the calendar, before realizing that doing so will result in basically stopping all the features of your application, if your entire application or only part of the application needs to access the function, you need to notify users and provide them with a way to jump to user settings, if possible, allow the user to manually grant access permissions.

In the example project, the method is to organize a new view in the story scene, this view contains a label that shows operation instructions and a button that enables the user to enter the setting interface of our application.

Again, some constraints involve correctly displaying some things at runtime. I won't talk about this detail here, because it is likely to be a little different for every execution operation.

The opinion I will point out is that the transparency of this view has been set to 0, so that if the user rejects authorization, I can display a gradually disappearing effect. the following figure shows the scenario where "NeedPermissionsView" is hidden:

Blob.png

Role of Event Store

The core of EventKit is EKEventStore. EKEventStore, which is the center of things. An instance of EKEventStore is created to provide developers with APIs for performing various read/write operations on the user's calendar and reminder list.

A View Controller that interacts with the calendar should have an instance that references EKEventStore, which is easily created-Here is an example:

ViewController. swift

 
 
  1. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
  2. let eventStore = EKEventStore() 
  3. // ... 

Check calendar authorization

Once we have an instance that references EKEventStore, we can do things like checking whether users are authorized to access their calendar. based on this, we can determine whether to request a license, and then determine the view to be displayed (Table view or license view required ).

It is important to check the calendar authorization. my suggestion is to check the view every time it appears (that is, in viewWillAppear (). Because the User grants the access permission for the first time and switches the settings, it is completely possible to reject the access. our applications need to make appropriate responses.

In the example project provided with this article, I 've created a function named checkCalendarAuthorizationStatus (). Here a peek at what it does:

In the example project provided in this article, I have created a function named checkCalendarAuthorizationStatus.

Next let's take a look at its implementation:

ViewController. swift

 
 
  1. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
  2. // ... 
  3. override func viewWillAppear(animated: Bool) { 
  4. checkCalendarAuthorizationStatus() 
  5. func checkCalendarAuthorizationStatus() { 
  6. let status = EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent) 
  7. switch (status) { 
  8. case EKAuthorizationStatus.NotDetermined: 
  9. // This happens on first-run 
  10. requestAccessToCalendar() 
  11. case EKAuthorizationStatus.Authorized: 
  12. // Things are in line with being able to show the calendars in the table view 
  13. loadCalendars() 
  14. refreshTableView() 
  15. case EKAuthorizationStatus.Restricted, EKAuthorizationStatus.Denied: 
  16. // We need to help them give us permission 
  17. needPermissionView.fadeIn() 
  18. default: 
  19. let alert = UIAlertView(title: "Privacy Warning", message: "You have not granted permission for this app to access your Calendar", delegate: nil, cancelButtonTitle: "OK") 
  20. alert.show() 
  21. // ... 

The key feature here is the implementation of EKEventStore's authorizationStatusForEntityType. The incoming EKEntityTypeEvent is used to interact with the user calendar. If we want to check their reminder permissions, we will use ekentitytytypereminder here.

The possible values of EKAuthorizationStatus use the corresponding case in the switch to execute the encapsulated logic code of independent functions for ease of reading.

Let's take a look at these features step by step.

Request calendar

As the title says, everything starts from here. every time our application loads and calls authorizationStatusForEntityType, The NotDetermined status is returned. at this point, we want to request access to the calendar.

To do this, define the requestAccessToCalendar function as follows:

 
 
  1. requestAccessToCalendar() 
  2. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
  3. // … 
  4. func requestAccessToCalendar() { 
  5. eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: { 
  6. (accessGranted: Bool, error: NSError!) in 
  7. if accessGranted == true { 
  8. // Ensure that UI refreshes happen back on the main thread! 
  9. dispatch_async(dispatch_get_main_queue(), { 
  10. self.loadCalendars() 
  11. self.refreshTableView() 
  12. }) 
  13. } else { 
  14. // Ensure that UI refreshes happen back on the main thread! 
  15. dispatch_async(dispatch_get_main_queue(), { 
  16. self.needPermissionView.fadeIn() 
  17. }) 
  18. }) 
  19. // … 

Our EKEventStore instance provides a function named requestAccessToEntityType. use EKEntityTypeEvent as the parameter for accessing the calendar. the interesting rest can be found in the encapsulated closure we provide.

There are three main things to note in implementation:

Two parameters passed to the closure are used to indicate whether the access permission is granted to the Bool type, and the other is NSError.

We need to call dispatch_async (), and indicate that we want to re-execute the UI refresh operation in the main queue column.

Self. needPermissionView. as an extension of a UIView In my operations, [Fade in/Out Animations as Class Extensions In Swift)] (https://github.com/andrewcbancroft/EventTracker/tree/ask-for-permission ).

Grant access permission! Load calendar and refresh table View

When the access is allowed, we can call the calendarsForEntityType function in the eventStore instance, and pass the EKEntityTypeEvent to capture the user calendar array and display it in our table view. Let's take a look at it below:

 
 
  1. loadCalendars() 
  2. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
  3. // ... 
  4. var calendars: [EKCalendar]? 
  5. // ... 
  6. func loadCalendars() { 
  7. self.calendars = eventStore.calendarsForEntityType(EKEntityTypeEvent) as? [EKCalendar] 
  8. func refreshTableView() { 
  9. calendarsTableView.hidden = false 
  10. calendarsTableView.reloadData() 
  11. // ... 

Access denied-display the view requiring permission

When the access is denied, We need to pop up the "Needs Permission View" created in the story scene ".

In this view, the above function is called again, so that users can directly jump to the settings page of our application so that they can authorize calendar access from there. this button is connected to an IBAction. the following is an example of implementing IBAction:

 
 
  1. goToSettingsButtonTapped() 
  2. class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 
  3. // ... 
  4. @IBAction func goToSettingsButtonTapped(sender: UIButton) { 
  5. let openSettingsUrl = NSURL(string: UIApplicationOpenSettingsURLString) 
  6. UIApplication.sharedApplication().openURL(openSettingsUrl!) 
  7. // ... 

Conclusion

This almost completes the start of using Event Kit! For other cases of the checkCalendarAuthorizationStatus () function, I simply analyzed the process allowed by the request.

I encourage you to jump to Github and start using Event Kit in your application to study the code in depth.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.