gpt4 book ai didi

macos - 请求 EventKit 访问 macOS SwiftUI

转载 作者:行者123 更新时间:2023-12-04 08:57:58 25 4
gpt4 key购买 nike

我正在尝试请求访问 SwiftUI MacOS 应用程序中的日历,但它立即拒绝了它。
下面是一些可测试的代码,突出显示了我想要实现的目标。非常感谢。
在我之前在 MacOS 上请求私有(private)信息的经验中,应该出现通知而不是 iOS 上的弹出窗口。
我仍在尝试为 SwiftUI 找出 EventKit,所以请原谅任何错误。

struct ContentView: View {

let eventStore = EKEventStore()

var body: some View {

Text("Test")
.onAppear{
checkCalendarAuthorizationStatus()
}

}


func checkCalendarAuthorizationStatus() {


switch EKEventStore.authorizationStatus(for: .event) {
case .authorized:
insertEvent(store: eventStore)
case .denied:
print("Access denied")
case .notDetermined:
// 3
eventStore.requestAccess(to: .event, completion:
{(granted: Bool, error: Error?) -> Void in
if granted {
self.insertEvent(store: eventStore)
} else {
print("Access denied")
}
})
default:
print("Case default")
}
}

func insertEvent(store: EKEventStore) {
// 1
let calendars = store.calendars(for: .event)

for calendar in calendars {
// 2
if calendar.title == "Calendar" {
// 3
let startDate = Date()
// 2 hours
let endDate = startDate.addingTimeInterval(2 * 60 * 60)

// 4
let event = EKEvent(eventStore: store)
event.calendar = calendar

event.title = "New Meeting"
event.startDate = startDate
event.endDate = endDate

// 5
do {
try store.save(event, span: .thisEvent)
}
catch {
print("Error saving event in calendar") }
}
}
}
}

最佳答案

您不应该检查状态,而是使用 EKEventStore().requestAccess(... 直接请求访问,如文档所述

/**
@method requestAccessToEntityType:completion:
@discussion Users are able to grant or deny access to event and reminder data on a per-app basis. To request access to
event and/or reminder data, call -requestAccessToEntityType:completion:. This will not block the app while
the user is being asked to grant or deny access.

Until access has been granted for an entity type, the event store will not contain any calendars for that
entity type, and any attempt to save will fail. The user will only be prompted the first time access is
requested; any subsequent instantiations of EKEventStore will use the existing permissions. When the user
taps to grant or deny access, the completion handler will be called on an arbitrary queue.
*/
@available(macOS 10.9, *)
open func requestAccess(to entityType: EKEntityType, completion: @escaping EKEventStoreRequestAccessCompletionHandler)
所以使用以下
func checkCalendarAuthorizationStatus() {

eventStore.requestAccess(to: .event, completion:
{(granted: Bool, error: Error?) -> Void in
if granted {
self.insertEvent(store: eventStore)
} else {
print("Access denied")
}
})
}
并确保 NSCalendarsUsageDescription Info.plist 中添加了描述.

关于macos - 请求 EventKit 访问 macOS SwiftUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63709783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com