Skip to content

Instantly share code, notes, and snippets.

@morphinewan
Created October 31, 2024 06:21
Show Gist options
  • Select an option

  • Save morphinewan/886204906a81d886481d5320a45155a9 to your computer and use it in GitHub Desktop.

Select an option

Save morphinewan/886204906a81d886481d5320a45155a9 to your computer and use it in GitHub Desktop.
添加一个订阅日历
import EventKit
class CalendarSubscriptionManager {
private let eventStore = EKEventStore()
// 添加日历订阅
func addCalendarSubscription(url: String, title: String, completion: @escaping (Bool, Error?) -> Void) {
// 首先请求日历访问权限
requestCalendarAccess { [weak self] granted, error in
guard granted else {
completion(false, error)
return
}
guard let self = self,
let subscriptionURL = URL(string: url) else {
completion(false, NSError(domain: "Invalid URL", code: -1, userInfo: nil))
return
}
// 创建新的订阅日历
let calendar = EKCalendar(for: .event, eventStore: self.eventStore)
calendar.title = title
calendar.source = self.findCalendarSource()
// 设置订阅URL
calendar.subscribedToURL = subscriptionURL
do {
// 保存日历
try self.eventStore.saveCalendar(calendar, commit: true)
completion(true, nil)
} catch {
completion(false, error)
}
}
}
// 请求日历访问权限
private func requestCalendarAccess(completion: @escaping (Bool, Error?) -> Void) {
if #available(iOS 17.0, *) {
// iOS 17及以上版本
eventStore.requestFullAccessToEvents { granted, error in
DispatchQueue.main.async {
completion(granted, error)
}
}
} else {
// iOS 17以下版本
eventStore.requestAccess(to: .event) { granted, error in
DispatchQueue.main.async {
completion(granted, error)
}
}
}
}
// 查找可用的日历源
private func findCalendarSource() -> EKSource? {
// 查找iCloud或本地日历源
return eventStore.sources.first { source in
source.sourceType == .calDAV || source.sourceType == .local
}
}
// 移除订阅的日历
func removeSubscribedCalendar(withTitle title: String, completion: @escaping (Bool, Error?) -> Void) {
let calendars = eventStore.calendars(for: .event)
guard let calendarToRemove = calendars.first(where: { $0.title == title }) else {
completion(false, NSError(domain: "Calendar not found", code: -1, userInfo: nil))
return
}
do {
try eventStore.removeCalendar(calendarToRemove, commit: true)
completion(true, nil)
} catch {
completion(false, error)
}
}
}
// 使用示例
let manager = CalendarSubscriptionManager()
// 添加订阅
manager.addCalendarSubscription(
url: "webcal://example.com/calendar.ics",
title: "My Subscribed Calendar"
) { success, error in
if success {
print("Calendar subscription added successfully")
} else {
print("Failed to add calendar subscription: \(error?.localizedDescription ?? "Unknown error")")
}
}
// 移除订阅
manager.removeSubscribedCalendar(withTitle: "My Subscribed Calendar") { success, error in
if success {
print("Calendar subscription removed successfully")
} else {
print("Failed to remove calendar subscription: \(error?.localizedDescription ?? "Unknown error")")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment