无法请求访问Swift 4.2中的IOS日历的权限

时间:2018-11-22 06:32:45

标签: ios iphone swift4 xcode10 ios12

我已经试过了前面的例子,要求向IOS日历添加项目。它们不适用于Xcode 10.1(Swift 4.2)。当我尝试编译代码时,出现错误。如果我注释掉以“ EKEventstore.requestAccess”开头的行,则代码将执行“ .not.Determined”循环。

错误是“实例成员'requestAccess'不能用于类型'EKEventStore';您是要使用此类型的值吗?”

任何人都可以找到我的错误,以便IOS应用程序有权向日历添加事件吗?

func SOGetPermissionCalendarAccess() {

    switch EKEventStore.authorizationStatus(for: .event) {

    case .authorized:
        print("Authorized")

    case .denied:
        print("Access denied")

    case .notDetermined:
        EKEventStore.requestAccess(to: .event, completion:
            {[weak self] (granted: Bool, error: Error?) -> Void in
                if granted {
                    print("Access granted")
                } else {
                    print("Access denied")
                }
        })

        print("Not Determined")
    default:
        print("Case Default")
        }

}

2 个答案:

答案 0 :(得分:2)

您应按如下所示创建事件存储实例,

let eventStore = EKEventStore()

之后,您可以如下所示进行许可请求,

switch EKEventStore.authorizationStatus(for: .event) {

        case .authorized:
            print("Authorized")

        case .denied:
            print("Access denied")

        case .notDetermined:
            eventStore.requestAccess(to: .event, completion:
                {(granted: Bool, error: Error?) -> Void in
                    if granted {
                        print("Access granted")
                    } else {
                        print("Access denied")
                    }
            })

            print("Not Determined")
        default:
            print("Case Default")
        }

有关更多信息,请参阅此link

答案 1 :(得分:0)

有关EKEventStore的Apple文档将执行reset()方法,这也无济于事。 我的解决方法是在requestAccess方法之后再次初始化EKEventStore。

private var store: EKEventStore
private var calendars: [EKCalendar] = []

private func requestAccessCalendars() {
    store.requestAccess(to: .event) { [weak self] (accessGranted, error) in
        if accessGranted {
            self?.store = EKEventStore() // <- second instance
            self?.store.refreshSourcesIfNecessary()

            self?.loadCalendars()
        }
    }
}

private func loadCalendars() {
    let cals = store.calendars(for: .event)
    for c in cals {
        if c.allowsContentModifications { // without birthdays, holidays etc'...
            calendars.append(c)
        }
    }
}