Notification サンプル
swift
.task(priority: .background) {
do {
let center = UNUserNotificationCenter.current()
let authorized = try await center.requestAuthorization(options: [.alert, .sound])
await MainActor.run {
isButtonDisabled = !authorized
}
} catch {
print("Error \(error)")
}
}
Button("send notification") {
Task(priority: .background) {
let center = UNUserNotificationCenter.current()
let authorization = await center.notificationSettings()
if authorization.authorizationStatus == .authorized {
await sendNotification()
}
}
}
.disabled(isButtonDisabled)
func sendNotification() async {
let content = UNMutableNotificationContent()
content.title = "Test Title"
content.body = "Test Body"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let id = "test-\(UUID())"
let request = UNNotificationRequest(identifier: id, content: content, trigger: trigger)
do {
let center = UNUserNotificationCenter.current()
try await center.add(request)
await MainActor.run {
print("done")
}
} catch {
print("Error \(error)")
}
}