OStack程序员社区-中国程序员成长平台

标题: ios - Swift - 在 applicationWillTerminate 中调用本地通知方法 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 18:59
标题: ios - Swift - 在 applicationWillTerminate 中调用本地通知方法

我有一个用于本地通知的公共(public)函数,我想在 applicationWillTerminate 中调用该函数。当我尝试这个时,没有任何反应。我确定本地通知功能没问题,因为当我在 viewDidLoad 中调用它时,它可以正常工作。


这是本地通知功能;

func scheduleLocalNotification(second: Double) {

    if #available(iOS 10.0, *) {
        let center = UNUserNotificationCenter.current()

        let content = UNMutableNotificationContent()
        content.badge = 1
        content.title = "Title!"
        content.body = "Message!"
        content.categoryIdentifier = "id"
        content.userInfo = ["key": "value"]
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: second, repeats: false)

        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        center.add(request)
    } else {
        // Fallback on earlier versions
    }
}

AppDelegate;

func applicationWillTerminate(_ application: UIApplication) {

        scheduleLocalNotification(second: 30.0)
        print("Terminating!")

        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

我在 SO 中搜索了类似的问题,发现了 2 个问题,但没有一个能解决我的问题。

Send local notification after termination app swift 2

Local notification on application termination


编辑:请求授权;

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        let launchedBefore = UserDefaults.standard.bool(forKey: "launchedBefore")
        if (!launchedBefore)  {
            if #available(iOS 10.0, *) {
                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                    if granted {
                        print("Authorization granted!")
                    } else {
                        print("Authorization not granted!")
                    }
                }
            } else {
                let settings = UIUserNotificationSettings(types: [.alert, .badge , .sound], categories: nil)
                UIApplication.shared.registerUserNotificationSettings(settings)
            }

            UserDefaults.standard.set(true, forKey: "launchedBefore")
        }

        // Override point for customization after application launch.
        return true
    }



Best Answer-推荐答案


您链接到的第二个问题的答案似乎相关 - 如果系统决定在后台终止您的应用程序,则不能保证调用 applicationWillTerminate

关于ios - Swift - 在 applicationWillTerminate 中调用本地通知方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42235023/






欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) Powered by Discuz! X3.4