gpt4 book ai didi

ios - Swift 4 如何从日历中获取所有事件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:02:09 25 4
gpt4 key购买 nike

我正在使用 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 年的谓词。这意味着,它不会给我所有事件!所以问题是:如何从日历中获取所有事件?如果可能,不使用日期!

感谢您以后的任何帮助或建议!

最佳答案

如果有人仍然想知道,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/

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