UNUserNotification is sending notification instantly in ios

804 Views Asked by At

I want to send a notification, on every 60 seconds interval, after application entered to the background. But when you enter the background, notification is sending immediately, after that every 60 seconds is sending notification. I don't want to send notification immediately, how can i do that?

Here is my code,

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
    }
    return true
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello,", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Some", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.badge = NSNumber(value: UIApplication.shared.applicationIconBadgeNumber + 1)
    content.categoryIdentifier = "com.mahmut.localNotification"

    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0, repeats: true)
    let request = UNNotificationRequest.init(identifier: "60Sec", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)

}
1

There are 1 best solutions below

3
On

try using it this way... instead of 4 you could use your own time... and later in your function you can use the timer concept to send a notification every 60 seconds.

    let triggerTime = (Int64(NSEC_PER_SEC) * 4)
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
        self.callYourFunction() 
    })