无法在Swift 4.2中请求访问iOS日历权限

5
我尝试了早期的例子,请求在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个回答

8

您应该按照以下方式创建事件存储实例:

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")
        }

请参考这个链接获取更多相关信息。该链接与IT技术有关。

这个可行。在“eventStore…”之后的那一行应该是“{(granted: Bool, error: Error?) -> Void in”因为没有使用self。 - Howard Matis
是的,正确的。如果您在完成块内没有使用“self”,则可以删除该部分。 - Natarajan
在 macOS 设置中,是否可以以编程方式更改用户拒绝的授权?或将应用程序授权重置为状态 .notDetermined? - Dawy

0

苹果关于EKEventStore的文档建议执行reset()方法,但这并没有帮助。 我的解决方案是在请求访问权限后重新初始化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)
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接