【问题标题】:How to send Local notifications when app is closed (swift)?应用程序关闭时如何发送本地通知(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)

【问题讨论】:

标签: ios swift uilocalnotification


【解决方案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)
        }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多