SwiftUI- 通知
通知是发送给用户的消息或警报,用于通知他们有关应用程序或服务的新信息、更新或事件。通知可以显示在设备的锁定屏幕上、通知中心中,也可以显示为横幅或警报,具体取决于系统和设置。
通知类型
在 SwiftUI 中,通知有两种类型:
本地通知:这些通知在设备本地安排和触发,无需互联网连接。例如,提醒应用程序可能会使用本地通知提醒用户即将发生的事件。
推送(远程)通知:这些通知从服务器发送到设备,通常通过 iOS 的 Apple 推送通知服务 (APNs) 或 Android 的 Firebase 云消息传递 (FCM) 等服务发送。例如,社交媒体应用可能会发送推送通知,通知用户有新消息。
通知的工作原理?
通知的工作原理按以下步骤说明:
权限请求:应用向用户请求权限以显示通知。
触发:通知由应用(本地)或服务器(推送)触发。
显示:通知以横幅、声音或徽章的形式显示在设备上。
交互:用户可以通过点击通知与通知进行交互,从而打开应用或执行操作(例如,回复消息)。
本地通知
SwiftUI 中的本地通知是指由应用本身触发的通知,通常不需要互联网连接。本地通知可以安排在特定时间或特定事件之后出现,并且它们可以包含标题、消息、声音和徽章等内容。
这些通知在设备本地管理,这意味着应用程序不依赖外部服务器来触发它们。
示例
以下 SwiftUI 程序用于创建本地通知。
import SwiftUI
import UserNotifications
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
// 当应用出现时请求通知权限
requestNotificationPermission()
}
}
}
// 请求显示通知的权限
func requestNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Notification permission granted")
} else if let error = error {
print("Error: \(error.localizedDescription)")
}
}
}
// 5 秒后安排本地通知的功能
func scheduleLocalNotification() {
let content = UNMutableNotificationContent()
content.title = "Reminder!"
content.body = "This is a local notification from SwiftUI."
content.sound = .default
// 5 秒后触发通知
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 {
print("Error scheduling notification: \(error.localizedDescription)")
} else {
print("Notification scheduled successfully!")
}
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate {
// 应用程序启动完成后将调用此函数
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
return true
}
// 当应用程序处于前台时处理通知
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// 通过横幅和声音显示通知
completionHandler([.banner, .sound])
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Local Notification Example").font(.title).padding()
// Button to schedule a local notification
Button(action: {
// 调用函数来安排通知
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
appDelegate.scheduleLocalNotification()
}
}) {
Text("Schedule Notification")
.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}.padding()
}
}
远程通知
推送(远程)通知是从服务器发送到用户设备的消息,即使应用未在前台运行也是如此。与由应用本身触发的本地通知不同,推送通知是从外部服务器发起的,通常通过 iOS 的 Apple 推送通知服务 (APN) 和 Android 的 Firebase Cloud Messaging (FCM) 等服务发起。
示例
以下 SwiftUI 程序用于创建推送通知。
import SwiftUI
import UserNotifications
import UIKit
@main
struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
.onAppear {
// 启动时请求通知权限
requestPushNotificationPermission()
}
}
}
// 请求推送通知权限
func requestPushNotificationPermission() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, error in
if granted {
print("Push notification permission granted")
} else if let error = error {
print("Error requesting permission: \(error.localizedDescription)")
}
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// 请求推送通知权限
requestPushNotificationPermission()
// 注册远程通知
application.registerForRemoteNotifications()
return true
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// 在此处理设备令牌
let deviceTokenString = deviceToken.map { String(format: "%02x", $0) }.joined()
print("Device Token: \(deviceTokenString)")
// 将此设备令牌发送到您的服务器
}
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
print("Failed to register for push notifications: \(error.localizedDescription)")
}
}
extension AppDelegate: UNUserNotificationCenterDelegate {
// 在前台处理推送通知
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.banner, .sound, .badge])
}
// 当用户点击通知时处理
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
print("User tapped on the notification: \(response.notification.request.content.body)")
completionHandler()
}
}
struct ContentView: View {
var body: some View {
VStack {
Text("Push Notifications Example")
.font(.title).padding()
Text("Push notifications will appear here when sent from the server.")
.padding()
// 用于测试或与通知交互的按钮
Button("Send Test Push Notification") {
// 触发服务器端操作以发送推送通知
}.padding()
.background(Color.blue)
.foregroundColor(.white)
.cornerRadius(10)
}
}
}

