如何在应用关闭时发送本地通知 (swift)?

How to send Local notifications when app is closed (swift)?

我有一个数据库,其中存储有过期日期的产品。当到期日期到期时,用户应该收到有关此的通知。但是如果用户关闭了他们的应用程序(杀死应用程序),这些通知也应该出现。问题:如何做到这一点?请告诉我代码。 我的代码是 (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
}

和(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)

如果您转到 AppDelegate,有一个名为 applicationWillTerminate 的方法,因此您只需调用发送位置的方法。

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    let viewControllerWithYourFunction = ViewControllerWithYourFunction()
    viewControllerWithYourFunction.sendLocation()
}

didFinishWithLaunchOptions

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

     if let launchOptions = launchOptions,
            let userInfo =  launchOptions[.remoteNotification] as? [AnyHashable: Any] {
            //some code here and post when needed like below
            NotificationCenter.default.post(name: NSNotification.Name("your notification name"),  object: nil)
        }
}