应用程序关闭时如何发送本地通知(swift)?
Posted
技术标签:
【中文标题】应用程序关闭时如何发送本地通知(swift)?【英文标题】:How to send Local notifications when app is closed (swift)? 【发布时间】:2018-09-22 06:28:46 【问题描述】:我有一个数据库,其中存储有过期日期的产品。当到期日期到期时,用户应该会收到有关此的通知。但是如果用户关闭了他们的应用程序(杀死应用程序),这些通知也应该出现。问题:如何做到这一点?请给我看代码。 我的代码是(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
和(视图控制器):
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)
【问题讨论】:
请参考***.com/questions/27732784/… @Vipul 谢谢,但您的代码是 ios @Tkas ***.com/questions/39713605/… @Vipul 谢谢你对我的帮助!但是当它在前台应用时,它会为应用程序编码 【参考方案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()
【讨论】:
我编辑了答案,将function
替换为method
。方法是一个函数,但它是类的一部分,就像在这种情况下一样。你可以了解更多here,来自兰恰诺的问候。【参考方案2】:
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)
【讨论】:
以上是关于应用程序关闭时如何发送本地通知(swift)?的主要内容,如果未能解决你的问题,请参考以下文章