如何实施Evenkit以请求权限

时间:2019-04-01 16:12:39

标签: swift macos

我正在构建一个Mac应用程序,该应用程序应在日历中添加一个提醒。构建没有错误也没有警告,但是当应用启动时,出现以下错误: “提醒失败,并显示错误,未授权对此事件存储的访问。”

我已经在网上搜索了在Mac上请求访问日历的正确方法,但是没有找到任何

我已经尝试将以下示例从ios转换为mac,但是失败:https://github.com/andrewcbancroft/EventTracker/tree/ask-for-permission

这是我的代码:

import Cocoa
import EventKit
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate 
{
    @IBOutlet weak var window: NSWindow!
    var eventStore = EKEventStore()
    var calendars: [EKCalendar]?
    func applicationDidFinishLaunching(_ aNotification: Notification)
    {
        let reminder = EKReminder(eventStore: self.eventStore)
        reminder.title = "Go to the store and buy milk"
        reminder.calendar = eventStore.defaultCalendarForNewReminders()
        do
        {
            try eventStore.save(reminder,
                                commit: true)
        } catch let error {
            print("Reminder failed with error \(error.localizedDescription)")
        }
    }
    func applicationWillTerminate(_ aNotification: Notification)
    {
        // Insert code here to tear down your application
    }
}

感谢您的关注。

2 个答案:

答案 0 :(得分:4)

例如,您必须在事件存储上调用requestAccess(to:completion:

company

答案 1 :(得分:0)

import Cocoa
import EventKit

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSTableViewDataSource, NSTableViewDelegate {

    @IBOutlet weak var window: NSWindow!

    var eventStore = EKEventStore()

    func applicationDidFinishLaunching(_ aNotification: Notification)
    {
        eventStore.requestAccess(to: .reminder)
        { (granted, error) in

            if let error = error
            {
                print(error)
                return
            }

            if granted
            {
                let reminder = EKReminder(eventStore: self.eventStore)
                reminder.title = "Go to the store and buy milk"
                reminder.calendar = self.eventStore.defaultCalendarForNewReminders()
                let date : NSDate = NSDate()
                let alarm : EKAlarm = EKAlarm (absoluteDate: date.addingTimeInterval(10) as Date)
                reminder.addAlarm(alarm)
                do
                {
                    try self.eventStore.save(reminder,commit: true)
                }
                catch let error {print("Reminder failed with error \(error.localizedDescription)")}
            }
        }
    }

    func applicationWillTerminate(_ aNotification: Notification)
    {
        // Insert code here to tear down your application
    }
}