一个没有实现的愿望所带来的痛苦,远远小于因后悔遗憾而带来的痛苦。因为前者面对的是无限广阔的开放未来,后者却是无法挽回的过去。——叔本华

首先是XCode创建一个新的项目

然后是修改ContentView文件,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//
// ContentView.swift
// backmoney
//
// Created by 阿超 on 2025/1/13.
//

import SwiftUI
import EventKit

struct ContentView: View {
@State private var showAlert = false
@State private var alertMessage = ""
let eventStore = EKEventStore()

var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundStyle(.tint)
Text("Hello, world!")

// 添加一个按钮
Button(action: {
// 请求访问权限并创建事件
requestAccessToCalendar { granted in
if granted {
createCalendarEvent()
} else {
showAlert = true
alertMessage = "没有权限访问日历"
}
}
}) {
Text("创建日历提醒")
.font(.title2)
.padding()
.foregroundColor(.white)
.background(Color.blue)
.cornerRadius(8)
}
}
.padding()
.alert(isPresented: $showAlert) {
Alert(title: Text("提示"), message: Text(alertMessage), dismissButton: .default(Text("确定")))
}
}

// 请求访问权限
func requestAccessToCalendar(completion: @escaping (Bool) -> Void) {
eventStore.requestAccess(to: .event) { granted, error in
if let error = error {
print("请求访问日历时出错:\(error.localizedDescription)")
completion(false)
}
completion(granted)
}
}

// 创建日历事件
func createCalendarEvent() {
let event = EKEvent(eventStore: eventStore)
event.title = "测试事件"
event.startDate = Date().addingTimeInterval(3600) // 一小时后
event.endDate = event.startDate.addingTimeInterval(3600) // 持续一小时
event.calendar = eventStore.defaultCalendarForNewEvents

do {
try eventStore.save(event, span: .thisEvent)
showAlert = true
alertMessage = "事件创建成功!"
} catch {
showAlert = true
alertMessage = "事件创建失败:\(error.localizedDescription)"
}
}
}

#Preview {
ContentView()
}