在Swift開發(fā)中弹沽,可以使用UNUserNotificationCenter
來添加一次性通知和定時(shí)通知弄痹。下面是一個(gè)簡單的示例代碼翼馆,演示如何添加一次性通知和定時(shí)通知:
- 導(dǎo)入
UserNotifications
框架奈搜,并請(qǐng)求用戶授權(quán)通知權(quán)限义钉。
import UIKit
import UserNotifications
class ViewController: UIViewController, UNUserNotificationCenterDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// 請(qǐng)求授權(quán)通知權(quán)限
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in
if let error = error {
print("Error requesting authorization for notifications: \(error.localizedDescription)")
}
}
// 設(shè)置UserNotificationCenter的代理
UNUserNotificationCenter.current().delegate = self
}
// 實(shí)現(xiàn)UserNotificationCenter的代理方法
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// 處理用戶對(duì)通知的響應(yīng)
completionHandler()
}
}
- 添加一次性通知。
func addOneTimeNotification() {
let content = UNMutableNotificationContent()
content.title = "One Time Notification"
content.body = "This is a one time notification."
content.sound = .default
// 通知觸發(fā)時(shí)間為當(dāng)前時(shí)間加上10秒
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
let request = UNNotificationRequest(identifier: "OneTimeNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error adding one time notification: \(error.localizedDescription)")
} else {
print("One time notification added successfully.")
}
}
}
- 添加定時(shí)通知浮毯。
func addScheduledNotification() {
let content = UNMutableNotificationContent()
content.title = "Scheduled Notification"
content.body = "This is a scheduled notification."
content.sound = .default
// 設(shè)置每周三晚上8點(diǎn)觸發(fā)通知
var dateComponents = DateComponents()
dateComponents.weekday = 4
dateComponents.hour = 20
dateComponents.minute = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "ScheduledNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Error adding scheduled notification: \(error.localizedDescription)")
} else {
print("Scheduled notification added successfully.")
}
}
}
關(guān)于UNUserNotificationCenter.current().delegate = self
設(shè)置一個(gè)代理對(duì)象并實(shí)現(xiàn)相應(yīng)的方法完疫,可以讓我們?cè)谕ㄖl(fā)送、接收和處理時(shí)獲取更多的信息和控制债蓝。下面是列出所有UNUserNotificationCenterDelegate
代理方法并對(duì)其進(jìn)行詳細(xì)解讀:
以下是 UNUserNotificationCenterDelegate
協(xié)議中的方法列表:
-
userNotificationCenter(_:willPresent:withCompletionHandler:)
:- 描述:在通知即將展示給用戶時(shí)調(diào)用此方法壳鹤。
- 參數(shù):
-
center
:通知中心對(duì)象。 -
notification
:待展示的通知對(duì)象饰迹。 -
completionHandler
:完成處理的閉包芳誓,在閉包中指定展示通知的方式。
-
- 返回值:無啊鸭。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { // 在這里處理通知的展示方式 completionHandler([.banner, .badge, .sound]) }
-
userNotificationCenter(_:didReceive:withCompletionHandler:)
:- 描述:當(dāng)接收到通知時(shí)調(diào)用此方法锹淌,不論是在前臺(tái)還是后臺(tái)。
- 參數(shù):
-
center
:通知中心對(duì)象赠制。 -
response
:包含接收到的通知和用戶的響應(yīng)信息的對(duì)象赂摆。 -
completionHandler
:完成處理的閉包,在閉包中指定對(duì)通知的處理結(jié)果钟些。
-
- 返回值:無烟号。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 在這里處理通知的響應(yīng) completionHandler() }
-
userNotificationCenter(_:openSettingsFor:)
:- 描述:當(dāng)用戶點(diǎn)擊通知設(shè)置按鈕時(shí)調(diào)用此方法。
- 參數(shù):
-
center
:通知中心對(duì)象政恍。 -
notification
:被點(diǎn)擊的通知對(duì)象汪拥。
-
- 返回值:無。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { // 在這里處理通知設(shè)置按鈕的點(diǎn)擊事件 }
-
userNotificationCenter(_:didReceive:attachmentOptions:withCompletionHandler:)
:- 描述:當(dāng)接收到帶附件的通知時(shí)調(diào)用此方法篙耗。
- 參數(shù):
-
center
:通知中心對(duì)象迫筑。 -
response
:包含接收到的通知和用戶的響應(yīng)信息的對(duì)象。 -
options
:附件的選項(xiàng)宗弯。 -
completionHandler
:完成處理的閉包脯燃,在閉包中指定對(duì)通知的處理結(jié)果。
-
- 返回值:無。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, attachmentOptions options: [UNNotificationAttachmentOptionsKey : Any], withCompletionHandler completionHandler: @escaping () -> Void) { // 在這里處理帶附件的通知的響應(yīng) completionHandler() }
-
userNotificationCenter(_:willPresent:for:)
:- 描述:當(dāng)通知將要在指定的應(yīng)用程序狀態(tài)下展示時(shí)調(diào)用此方法。
- 參數(shù):
-
center
:通知中心對(duì)象织阅。 -
notification
:待展示的通知對(duì)象便瑟。 -
applicationState
:應(yīng)用程序的狀態(tài)坟募。
-
- 返回值:展示通知的選項(xiàng)。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, for applicationState: UIApplicationState) -> UNNotificationPresentationOptions { // 在這里指定通知展示的方式 return [.alert, .sound] }
-
userNotificationCenter(_:didReceive:withCompletionHandler:)
:- 描述:當(dāng)接收到通知時(shí)調(diào)用此方法邑狸,不論是在前臺(tái)還是后臺(tái)懈糯。
- 參數(shù):
-
center
:通知中心對(duì)象。 -
response
:包含接收到的通知和用戶的響應(yīng)信息的對(duì)象单雾。 -
completionHandler
:完成處理的閉包赚哗,在閉包中指定對(duì)通知的處理結(jié)果。
-
- 返回值:無硅堆。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // 在這里處理通知的響應(yīng) let requestData = response.notification.request.content.userInfo if let customData = requestData["customData"] as? String { print("接收到自定義數(shù)據(jù):\(customData)") } completionHandler() }
- 解讀:該方法在接收到通知并且用戶響應(yīng)了該通知時(shí)調(diào)用屿储。通過
response
參數(shù)可以獲取到通知的內(nèi)容和用戶的響應(yīng)信息。在這個(gè)例子中渐逃,我們通過訪問userInfo
字典來獲取自定義數(shù)據(jù)够掠,并進(jìn)行相應(yīng)的處理。
-
userNotificationCenter(_:openSettingsFor:)
:- 描述:當(dāng)用戶點(diǎn)擊通知設(shè)置按鈕時(shí)調(diào)用此方法茄菊。
- 參數(shù):
-
center
:通知中心對(duì)象疯潭。 -
notification
:被點(diǎn)擊的通知對(duì)象。
-
- 返回值:無面殖。
- 代碼示例:
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) { // 在這里處理通知設(shè)置按鈕的點(diǎn)擊事件 if let settingsUrl = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(settingsUrl, options: [:], completionHandler: nil) } }
UNUserNotificationCenter
是用于管理應(yīng)用程序的通知中心竖哩,它提供了一系列屬性和方法來管理和處理通知。
以下是 UNUserNotificationCenter
類的常用屬性和方法以及它們的詳細(xì)解讀和代碼實(shí)現(xiàn):
屬性(Properties)
-
current
:- 描述:獲取當(dāng)前應(yīng)用程序的通知中心對(duì)象脊僚。
- 代碼實(shí)現(xiàn):
let center = UNUserNotificationCenter.current()
方法(Methods)
-
getNotificationSettings(completionHandler:)
:- 描述:獲取應(yīng)用程序的通知設(shè)置相叁。
- 參數(shù):
-
completionHandler
:完成處理的閉包,在閉包中獲取通知設(shè)置信息辽幌。
-
- 返回值:無增淹。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().getNotificationSettings { settings in print("通知設(shè)置:\(settings)") }
-
requestAuthorization(options:completionHandler:)
:- 描述:請(qǐng)求用戶授權(quán)進(jìn)行通知推送。
- 參數(shù):
-
options
:請(qǐng)求授權(quán)的選項(xiàng)舶衬,如.badge
,.sound
,.alert
等埠通。 -
completionHandler
:授權(quán)請(qǐng)求的結(jié)果處理閉包。
-
- 返回值:無逛犹。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert]) { granted, error in if granted { print("用戶已授權(quán)通知") } else { print("用戶未授權(quán)通知") } }
-
add(request:withCompletionHandler:)
:- 描述:向通知中心添加一個(gè)通知請(qǐng)求端辱。
- 參數(shù):
-
request
:要添加的通知請(qǐng)求對(duì)象。 -
completionHandler
:添加完成的處理閉包虽画。
-
- 返回值:無舞蔽。
- 代碼實(shí)現(xiàn):
let content = UNMutableNotificationContent() content.title = "新消息" content.body = "您有一條新消息" let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false) let request = UNNotificationRequest(identifier: "myNotification", content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { print("添加通知請(qǐng)求失敗:\(error.localizedDescription)") } else { print("通知請(qǐng)求添加成功") } }
-
removePendingNotificationRequests(withIdentifiers:)
:- 描述:移除指定標(biāo)識(shí)符的待發(fā)送通知請(qǐng)求码撰。
- 參數(shù):
-
identifiers
:要移除的通知請(qǐng)求的標(biāo)識(shí)符數(shù)組渗柿。
-
- 返回值:無。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: ["notification1", "notification2"])
-
removeDeliveredNotifications(withIdentifiers:)
:- 描述:移除指定標(biāo)識(shí)符的已經(jīng)發(fā)送的通知。
- 參數(shù):
-
identifiers
:要移除的通知的標(biāo)識(shí)符數(shù)組朵栖。
-
- 返回值:無颊亮。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["notification1", "notification2"])
-
getNotificationCategories(completionHandler:)
:- 描述:獲取應(yīng)用程序當(dāng)前注冊(cè)的通知分類。
- 參數(shù):
-
completionHandler
:完成處理的閉包陨溅,在閉包中獲取通知分類信息终惑。
-
- 返回值:無。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().getNotificationCategories { categories in print("已注冊(cè)的通知分類:\(categories)") }
-
setNotificationCategories(_:)
:- 描述:設(shè)置應(yīng)用程序的通知分類门扇。
- 參數(shù):
-
categories
:要設(shè)置的通知分類集合雹有。
-
- 返回值:無。
- 代碼實(shí)現(xiàn):
let category = UNNotificationCategory(identifier: "myCategory", actions: [], intentIdentifiers: [], options: []) UNUserNotificationCenter.current().setNotificationCategories([category])
-
delegate
:- 描述:通知中心的代理對(duì)象臼寄,用于處理通知相關(guān)的事件和回調(diào)霸奕。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().delegate = self
-
add(_ request: UNNotificationRequest, withCompletionHandler completionHandler: ((Error?) -> Void)?)
:- 描述:添加一個(gè)通知請(qǐng)求,并指定完成處理的閉包吉拳。
- 參數(shù):
-
request
:要添加的通知請(qǐng)求對(duì)象质帅。 -
completionHandler
:添加完成的處理閉包。
-
- 返回值:無合武。
getDeliveredNotifications(completionHandler:)
:
- 描述:獲取已經(jīng)發(fā)送的通知列表临梗。
- 參數(shù):
-
completionHandler
:完成處理的閉包,在閉包中獲取已發(fā)送通知的列表稼跳。
-
- 返回值:無盟庞。
- 代碼實(shí)現(xiàn):
UNUserNotificationCenter.current().getDeliveredNotifications { notifications in for notification in notifications { print(notification.request.identifier) } }