简体   繁体   English

(iOS Swift)在应用程序和Today Extension之间共享EKEventStore和访问

[英](iOS Swift) Share EKEventStore and access between app and Today Extension

I created an app that is mainly used by a Today Extension. 我创建了一个主要由Today Extension使用的应用程序。 It has to have access to the calendar because the widget displays upcoming events. 它必须有权访问日历,因为窗口小部件将显示即将发生的事件。 Now I want the "host app" to have a list of all the users calendars and lets the user decide which calendars the widget should consider getting the events from. 现在,我希望“主机应用程序”具有所有用户日历的列表,并让用户决定小部件应考​​虑从中获取事件的日历。

My understanding is that the EKEventStore() initializer should not be called multiple times (by the widget and the host app in this example). 我的理解是,不应多次调用EKEventStore()初始化程序(在此示例中,由窗口小部件和主机应用程序调用)。 Is there an easy way to only ask once for the permission to use the calendar (regardless whether the user first interacts with the host app or the widget) and share the permissions or do I have to check for permission in both the widget and the host app? 是否有一种简单的方法仅询问一次使用日历的权限(无论用户是否首先与主机应用程序或窗口小部件进行交互)并共享该权限,还是我必须在窗口小部件和主机中都检查权限?应用程式? Also, how should I ideally deal with using the EKEventStore() initializer in both the widget and the app? 此外,理想情况下,我该如何在小部件和应用程序中同时使用EKEventStore()初始化程序?

To answer the questions for future reference: This is my solution to the problem of only writing the code to check for calendar access once. 回答这些问题以供将来参考:这是我的解决方案,它仅编写一次代码即可检查日历访问权限。 I created an extension of EKEventStore class which lets me call a function which returns the status as a boolean. 我创建了EKEventStore类的扩展,该扩展允许我调用一个将状态返回为布尔值的函数。 This makes usage of this in different targets much more clean 这使得在不同目标中使用此方法更加干净

public extension EKEventStore {

func hasCalendarAccess() -> Bool {
    let status = EKEventStore.authorizationStatusForEntityType(EKEntityType.Event)
    var accessGranted : Bool = false

    switch(status){
    case EKAuthorizationStatus.NotDetermined:
        requestAccessToEntityType(EKEntityType.Event, completion: {
            (returnValue: Bool, error: NSError?) in
            accessGranted = returnValue
        })
    case EKAuthorizationStatus.Authorized:
        accessGranted = true
    case EKAuthorizationStatus.Denied:
        accessGranted = false
    case EKAuthorizationStatus.Restricted:
        print("restricted")
        accessGranted = false
    }

    return accessGranted
}

Thanks to dan for the answer regarding multiple instances of EKEventStore 感谢dan为EKEventStore的多个实例提供的答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM