SwiftUI应用通知功能实现遇阻,寻求技术解决方案
SwiftUI 通知功能实现指南
一、请求通知权限
首先需要向用户申请通知权限,可在App启动时完成:
import UserNotifications import SwiftUI @main struct NotificationDemoApp: App { init() { requestNotificationPermission() } var body: some Scene { WindowGroup { ContentView() } } private func requestNotificationPermission() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { granted, error in if let error = error { print("权限请求失败: \(error.localizedDescription)") } if granted { print("通知权限已授予") DispatchQueue.main.async { UIApplication.shared.registerForRemoteNotifications() } } } } }
二、本地通知实现
通过按钮触发本地通知的示例:
struct ContentView: View { var body: some View { Button("触发10秒后通知") { scheduleLocalNotification() } } private func scheduleLocalNotification() { let content = UNMutableNotificationContent() content.title = "测试通知" content.body = "这是一条SwiftUI本地通知" content.sound = .default // 设置10秒后触发,不重复 let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false) let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger) UNUserNotificationCenter.current().add(request) { error in if let error = error { print("添加通知请求失败: \(error.localizedDescription)") } } } }
三、远程推送通知配置(APNs)
基础配置步骤
- 在Apple开发者后台开启App的
Push Notifications服务 - 生成并配置推送证书或密钥,确保后端可以正常调用APNs接口
SwiftUI中处理推送回调
通过UIApplicationDelegateAdaptor适配推送代理:
class AppDelegate: NSObject, UIApplicationDelegate, UNUserNotificationCenterDelegate { // 成功获取设备Token func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined() print("设备Token: \(token)") // 将token发送至你的后端服务器 } // 注册远程通知失败 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("注册远程通知失败: \(error.localizedDescription)") } // App前台时显示通知 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { completionHandler([.alert, .sound, .badge]) } // 处理用户点击通知的操作 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { let userInfo = response.notification.request.content.userInfo print("点击通知获取到的信息: \(userInfo)") completionHandler() } } // 在App结构体中关联代理 @main struct NotificationDemoApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate init() { requestNotificationPermission() UNUserNotificationCenter.current().delegate = appDelegate } // 之前的requestNotificationPermission方法... }
常见问题排查
- 检查系统设置中App的通知权限是否开启
- 本地通知在App前台时,必须实现
willPresent回调才能弹出通知 - 远程推送需确保设备Token正确传递给后端,且后端使用的证书/密钥与App的Bundle ID匹配
内容的提问来源于stack exchange,提问作者lhy
相关产品推荐
相关产品推荐

