I have a database where products with expiration dates are stored. When the expiry date expires, the user should receive a notification about this. But these notifications should also come if the user turned off their application (kill app). Question: how to do this? Show me the code, please. My code is (AppDelegate):
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in }
return true
}
and (ViewController):
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "\(overdueProductsStringArray)"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "t", content: content, trigger: trigger)
center.add(request, withCompletionHandler: nil)
If you go to AppDelegate there is a method called applicationWillTerminate
so you just need to call your method that send locations.
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
let viewControllerWithYourFunction = ViewControllerWithYourFunction()
viewControllerWithYourFunction.sendLocation()
}