import Foundation
import UserNotifications
class APNSAuthManager: ObservableObject {
let center = UNUserNotificationCenter.current()
func requestAuth() {
center.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if error != nil {
// Handle the error here.
}
print("user allowed")
// Enable or disable features based on the authorization.
}
}
func getSetting() {
center.getNotificationSettings { settings in
guard (settings.authorizationStatus == .authorized) ||
(settings.authorizationStatus == .provisional) else { return }
if settings.alertSetting == .enabled {
// Schedule an alert-only notification.
print("alertSetting")
} else {
// Schedule a notification with a badge and sound.
print("badge and sound")
}
}
}
func sendLocalNote() {
// payload
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Local Note Title!", arguments: nil)
content.subtitle = "subtitle"
content.body = NSString.localizedUserNotificationString(forKey: "Local Note Body", arguments: nil)
content.sound = .default
content.badge = 1
// trigger
let date = Date().addingTimeInterval(5)
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
// request
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) // Schedule the notification.
center.add(request) { (error : Error?) in
if error != nil {
// Handle any errors
}
print("local note sent!")
}
}
}
ContentView.swift
import SwiftUI
import UserNotifications
struct ContentView: View {
@ObservedObject var manager = APNSAuthManager()
var body: some View {
Button(action: {
manager.sendLocalNote()
}, label: {
Text("Send the local note")
})
Text("good")
.onAppear {
manager.requestAuth()
manager.getSetting()
}
}
}