Swift - 在applicationWillTerminate中调用本地通知方法

时间:2017-02-14 19:54:13

标签: ios swift uilocalnotification unusernotificationcenter

我有一个用于本地通知的公共函数,我想在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
    }

2 个答案:

答案 0 :(得分:0)

您链接到的第二个问题的答案似乎相关 - 如果系统决定在后台处理您的应用,则无法保证调用applicationWillTerminate

答案 1 :(得分:0)

只是关于applicationWillTerminate的注释:正如Apple所述,并且“Uncommon”说,不能保证被调用。

但我认为这是一个设计问题:

a)如果您想添加本地通知,请在用户设置后立即执行。

b)如果您通过“applicationWillTerminate”传递保存cpu时间仅在退出时调用“添加通知”,请确保每次都没有大的惩罚保存通知。作为std行为,在iOS中我们应该在用户设置后立即保存所有内容。

在我的应用中,我只是在“后退”或“关闭”中添加通知。

c)务必控制/重置已设置的通知。

如果您只是测试iOS行为,那么您处于角落边缘,请参阅此处的“eskimo”答案:

https://forums.developer.apple.com/thread/13557