jsdw_ios/QuickLocation/Manager/Notification/TimeSpecificNotificationMan...

127 lines
4.3 KiB
Swift
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// TimeSpecificNotificationManager.swift
// SHECommunity
//
// Created by Lin on 2025/7/29.
//
import UIKit
import UserNotifications
class TimeSpecificNotificationManager {
static let shared = TimeSpecificNotificationManager()
private init() {}
// 1.
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if granted {
print("通知权限已允许")
} else {
print("通知权限被拒绝,无法发送通知")
}
}
}
// 2.
/// - Parameters:
/// - title:
/// - body:
/// - date: 2025-08-01 09:30:00
/// - identifier:
func scheduleOneTimeNotification(
title: String,
body: String,
at date: Date,
identifier: String = UUID().uuidString
) {
//
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default //
content.badge = 1 //
// Date DateComponents
let components = Calendar.current.dateComponents(
[.year, .month, .day, .hour, .minute], //
from: date
)
//
let trigger = UNCalendarNotificationTrigger(
dateMatching: components,
repeats: false //
)
//
let request = UNNotificationRequest(
identifier: identifier,
content: content,
trigger: trigger
)
//
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("通知添加失败:\(error.localizedDescription)")
} else {
print("通知已设置,将在 \(date) 触发")
}
}
}
// 3.
/// - Parameters:
/// - title:
/// - body:
/// - hour: 24 9 9
/// - minute: 30 30
/// - identifier:
func scheduleRepeatingNotification(
title: String,
body: String,
hour: Int,
minute: Int,
identifier: String = UUID().uuidString
) {
let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = .default
content.badge = 1
// /// repeats: true
var dateComponents = DateComponents()
dateComponents.hour = hour // 99
dateComponents.minute = minute // 3030
//
let trigger = UNCalendarNotificationTrigger(
dateMatching: dateComponents,
repeats: true // dateComponents
)
//
let request = UNNotificationRequest(
identifier: identifier,
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("重复通知添加失败:\(error.localizedDescription)")
} else {
print("每天 \(hour):\(minute) 的重复通知已设置")
}
}
}
// 4.
func cancelNotification(identifier: String) {
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: [identifier])
print("已取消标识为 \(identifier) 的通知")
}
}