import SwiftUI
import UserNotifications
struct ContentView: View {
@State private var showingPermissionAlert = false
@State private var alertMessage = ""
var body: some View {
VStack {
Button("Schedule Alert") {
scheduleNotification()
}
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(8)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.white)
.alert(isPresented: $showingPermissionAlert) {
Alert(title: Text("Notification Permission"), message: Text(alertMessage), dismissButton: .default(Text("OK")))
}
}
func scheduleNotification() {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { settings in
switch settings.authorizationStatus {
case .notDetermined:
center.requestAuthorization(options: [.alert, .sound]) { granted, error in
DispatchQueue.main.async {
if granted {
sendNotification()
} else {
alertMessage = "Permission was denied. Please enable notifications in settings."
showingPermissionAlert = true
}
}
}
case .authorized, .provisional:
DispatchQueue.main.async {
sendNotification()
}
case .denied:
DispatchQueue.main.async {
alertMessage = "Permission was denied. Please enable notifications in settings."
showingPermissionAlert = true
}
default:
break
}
}
}
func sendNotification() {
let content = UNMutableNotificationContent()
content.title = "Reminder"
content.body = "This is your local notification!"
content.sound = UNNotificationSound.default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
DispatchQueue.main.async {
alertMessage = "Failed to schedule notification: \(error.localizedDescription)"
showingPermissionAlert = true
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}This solution uses SwiftUI and the UserNotifications framework to schedule a local notification.
The button labeled Schedule Alert triggers scheduleNotification(). This function first checks the current notification permission status.
If permission is not determined, it requests authorization. If granted, it schedules the notification; if denied, it shows an alert.
If permission is already authorized or provisional, it schedules the notification immediately.
If permission is denied, it shows an alert informing the user.
The notification is set to fire after 5 seconds with a title and body as required.
Alerts are shown using SwiftUI's .alert modifier bound to state variables.