我有一个 NSObject 类,它由一个基本的 EKCalendarChooser 实现组成,我无法获得委托函数calendarChooserDidFinish
、calendarChooserSelectionDidChange
和calendarChooserDidCancel
工作。我不确定是否所有内容都在 NSObject 中,但我想将此代码与其他文件分开。
我尝试了很多故障排除,例如不将委托方法保留在扩展名下,甚至为 EKCalendarChooser 创建一个全局变量,因为我发现这篇文章指出可以在这样的上下文中取消引用非全局项。总的来说,我可以让控制器弹出,这正是我想要的方式,但委托方法不起作用。下面是整个代码,在我的主视图控制器中,我得到了这个显示 AddAppointments(parentViewController: self).chooseCalendarTapped()
import UIKit
import EventKitUI
class Cal: NSObject {
let eventStore = EKEventStore()
var parentViewController: UIViewController
var CalendarChooser: EKCalendarChooser = EKCalendarChooser()
init(parentViewController: UIViewController) {
self.parentViewController = parentViewController
super.init()
}
func chooseCalendarTapped() {
let authStatus = EKEventStore.authorizationStatus(for: .event)
switch authStatus {
case .authorized:
showCalendarChooser()
case .notDetermined:
requestAccess()
case .denied:
// Explain to the user that they did not give permission
break
case .restricted:
break
@unknown default:
preconditionFailure("Who knows what the future holds ")
}
}
func requestAccess() {
eventStore.requestAccess(to: .event) { (granted, error) in
if granted {
// may not be called on the main thread..
DispatchQueue.main.async {
self.showCalendarChooser()
}
}
}
}
func showCalendarChooser() {
CalendarChooser = EKCalendarChooser(selectionStyle: .single, displayStyle: .allCalendars, entityType: .event, eventStore: eventStore)
// customization
CalendarChooser.showsDoneButton = true
CalendarChooser.showsCancelButton = true
// dont forget the delegate
CalendarChooser.delegate = self
let nvc = UINavigationController(rootViewController: CalendarChooser)
parentViewController.present(nvc, animated: true, completion: nil)
}
}
extension Cal : EKCalendarChooserDelegate {
func calendarChooserDidFinish(_ calendarChooser: EKCalendarChooser) {
print(calendarChooser.selectedCalendars)
// dismiss(animated: true, completion: nil)
}
func calendarChooserSelectionDidChange(_ calendarChooser: EKCalendarChooser) {
print("Changed selection")
}
func calendarChooserDidCancel(_ calendarChooser: EKCalendarChooser) {
print("Cancel tapped")
// dismiss(animated: true, completion: nil)
}
}