我使用的是 Swift 4.1。我想编写一个函数来收集 iOS 日历应用程序中所有日历中的所有事件。感谢stackoverflow上的这个答案:How to get all Events out of a Calendar (Swift)我能够编写自己的 class
并将其称为 Cale
。请看这个:
import UIKit
import EventKit
class Cale {
private func createDate(year: Int) -> Date {
var components = DateComponents()
components.year = year
components.timeZone = TimeZone(secondsFromGMT: 0)
return Calendar.current.date(from: components)!
}
private let eventStore = EKEventStore()
private func get() {
let calendars = eventStore.calendars(for: .event)
for calendar in calendars {
// This checking will remove Birthdays and Hollidays callendars
guard calendar.allowsContentModifications else {
continue
}
let start = createDate(year: 2016)
let end = createDate(year: 2025)
print("start: \(start)")
print(" end: \(end)")
let predicate = eventStore.predicateForEvents(withStart: start, end: end, calendars: [calendar])
print("predicate: \(predicate)")
let events = eventStore.events(matching: predicate)
for event in events {
print(" title: \(event.title!)")
print("startDate: \(event.startDate!)")
print(" endDate: \(event.endDate!)")
}
}
}
func checkStatusAndGetAllEvents() {
let currentStatus = EKEventStore.authorizationStatus(for: EKEntityType.event)
switch currentStatus {
case .authorized:
//print("authorized")
self.get()
case .notDetermined:
//print("notDetermined")
eventStore.requestAccess(to: .event) { accessGranted, error in
if accessGranted {
self.get()
} else {
print("Change Settings to Allow Access")
}
}
case .restricted:
print("restricted")
case .denied:
print("denied")
}
}
}
非常简单的类,你可以使用它,它可以工作,但有一个异常(exception)。
主要函数是 get()
在这个函数中,我基于两个日期创建谓词:开始和结束。如您所见,开始日期是:
2016-01-01 00:00:00 +0000
结束日期是:
2025-01-01 00:00:00 +0000
但是如果我们运行程序,我们会看到谓词是这样的:
CADEventPredicate start:01/01/2016, 03:00; end:01/01/2020, 03:00; cals 2 )
仅从 2016 年到 2020 年,4 年!我已经在不同的日期对其进行了测试,但我可以得到最大间隔为 4 年的谓词。这意味着,它不会给我所有的事件!所以问题是:如何从日历中获取所有事件?如果可能,不要使用日期!
感谢您对 future 的任何帮助或建议!
如果有人仍然想知道,Apple 故意将其限制为四年。
来自 predicateForEvents(withStart:end:calendars :
For performance reasons, this method matches only those events within a four year time span. If the date range between startDate and endDate is greater than four years, it is shortened to the first four years.
如果您想要一个更长的范围,我想您必须将其包装在您自己的函数中以将其拆分为四年 block 。
关于ios - Swift 4 如何从日历中获取所有事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439574/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |