我有一个数据库,用于存储具有到期日期的产品。当到期日期到期时,用户应收到有关此的通知。但是,如果用户关闭了他们的应用程序(杀死应用程序),这些通知也应该出现。问题:该怎么做?请告诉我代码。 我的代码是(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)
答案 0 :(得分:1)
如果您转到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()
}
答案 1 :(得分:0)
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)
}
}