SwiftUI 前台显示消息推送
问题描述
今天捣鼓了一天消息推送,想要实现的效果是 SwiftUI 中软件在前台运行时也可以进行消息推送(本地)。但是 UserNotifications 里面默认是只有软件在后台才能推送,如果软件运行在前台是没有效果的。🖕
苹果这个坑爹玩意,IOS 每次版本更新都有很多变化,很多以前的解决方案都没法用。
终于在晚上准备睡觉前找到了一个目前可用解决方案(以后不清楚)。
解决方案
由于我用的是比较新版本的 SwiftUI,所以没有 AppDelegate.swift 了,那么在 xxxApp.swift 文件中添加代码如下:
- 不要忘记在 @main 里面还有一行代码!
class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// Show local notification in foreground
UNUserNotificationCenter.current().delegate = self
return true
}
}
// Conform to UNUserNotificationCenterDelegate to show local notification in foreground
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.badge, .sound])
}
}
@main
struct wisdom_fire_controlApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
时至 2022.2.10,亲测有效,后面就不知道了。
附上 google 到的解决方案原帖:https://ishtiz.com/swift/how-to-show-local-notification-when-the-app-is-foreground。
百度搜出来的 SwiftUI 相关资料基本被某人以收费的名义霸占了… 实际上我告诉大家,那个人的代码我在 google 不止见过一次,见过很多篇英文文章甚至源码都和他一模一样。感觉只要他的代码里出现英文注释,基本就是抄的…
最后提一句,IOS 开发真的锻炼心态和英语。。。现在已经快习惯去谷歌翻英文文档了。放以前看到英文页面我直接 X 掉,现在不行哟,SwiftUI 相关的资料实在是太少了,只能去国外翻最新资料。。。。