今天,我已将 Xcode 更新至 15.0,将 iPhone 更新至 iOS 17,但现在我在日历中写入 EKEvent 的代码不再起作用。它在早期版本的 iOS 中运行良好。我是否存在兼容性问题或者还有其他原因?
错误是这样的:
错误:-requestAccessToEntityType:completion: 已弃用 - 不再允许调用此方法。相反,请使用 -requestFullAccessToEventsWithCompletion:、-requestWriteOnlyAccessToEventsWithCompletion: 或 -requestFullAccessToRemindersWithCompletion:
我的代码如下所示:
func accesCalenderToAddEvent() {
let eventStore: EKEventStore = EKEventStore()
eventStore.requestAccess(to: EKEntityType.event) { granted, error in
DispatchQueue.main.async {
if (granted) && (error == nil) {
let event = EKEvent(eventStore: self.eventStore)
event.title = "Event 1"
event.startDate = Date()
event.endDate = Date()
let eventController = EKEventEditViewController()
eventController.event = event
eventController.eventStore = eventStore
eventController.editViewDelegate = self
self.present(eventController, animated: true, completion: nil)
} else {
let alertController = UIAlertController(title: "Calendar Permission Required", message: "Please enable Calender permissions in settings.", preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: {(cAlertAction) in
//Redirect to Settings app
UIApplication.shared.open(URL(string:UIApplication.openSettingsURLString)!)
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}
请向我建议 iOS 17 的解决方案,因为在早期版本中它适合我。
提前致谢。
最佳答案
iOS 17 的权限范围已更改为包括读取、写入和完全访问权限,而 iOS 16 仅具有完全访问权限。当您在 iOS 17 上使用 eventStore.requestAccess() 时,这会导致错误,但在 iOS 16 上则不会。
弃用通知:https://developer.apple.com/documentation/eventkit/ekeventstore/1507547-requestaccesstoentitytype
要在 iOS 17 中提供支持,请编写如下代码:
if #available(iOS 17.0, *) {
eventStore.requestWriteOnlyAccessToEvents { granted, error in
DispatchQueue.main.async {
//write the existing logic here
}
}
}else {
//put the old code here so it’s been working in earlier versions before iOS 17.
}
注意:
If you are only using EKEventEditViewController then you no need to take the any permission as per this official doc: Documentation
关于ios - requestAccessToEntityType :completion: has been deprecated calling this is no longer allowed. 改为使用 requestFullAccessToEventsWithCompletion:,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77185358/