用户离开应用程序IOS时如何向他们发送本地通知

时间:2018-08-07 09:19:50

标签: ios xcode notifications notificationcenter

我正在开发一个计时器应用程序,如果用户离开该应用程序,该应用程序应终止。我希望在他们离开应用程序时将通知发送给用户。此通知警告用户,如果计时器没有立即返回应用,计时器将终止 我已经看过UNNotficationTrigger,但是如果要多次警告用户,我不会尝试重复该通知。

如何检测用户何时不在应用程序之外,然后发送通知以警告他们返回到应用程序? 预先谢谢你

代码:

 @IBAction func start(_ sender: Any) {


    startTimer()    

    let content = UNMutableNotificationContent()

    content.title = "WARNING: Return to 4ocus"

    content.subtitle = ""

    content.body = "Go back to 4ocus or risk losing 4ocus points"

    content.badge = 1



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



let request  = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

 @IBAction func start(_ sender: Any) {

    startTimer()

    let content = UNMutableNotificationContent()

    content.title = "WARNING: Return to 4ocus"

    content.subtitle = ""

    content.body = "Go back to 4ocus or risk losing 4ocus points"

    content.badge = 1

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


let request  = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

1 个答案:

答案 0 :(得分:0)

func applicationWillTerminate(_ application: UIApplication) {

    let content = UNMutableNotificationContent()

    //adding title, subtitle, body and badge
    content.title = "Hey if you will not come back"
    content.subtitle = "your timer will be killed"
    content.body = ""
    content.badge = 1

    //getting the notification trigger
    //it will be called after 5 seconds
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

    //getting the notification request
    let request = UNNotificationRequest(identifier: "SimplifiedIOSNotification", content: content, trigger: trigger)

    //adding the notification to notification center
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

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

,还将相同的代码放入appdelegate的willforeground方法中,以了解用户是否要离开应用程序

   func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

将此方法放到您的appdelegate中,如果定义了func applicationWillTerminate(_ application:UIApplication),则仅放置代码:)