【问题标题】:App running in the background send local notifications后台运行的应用程序发送本地通知
【发布时间】:2018-12-03 11:02:28
【问题描述】:

如何在应用程序在后台运行时发送本地通知?在 Swift 4 中。我的应用程序持续使用 Json 文件,我希望应用程序继续运行,以便向用户发送本地通知。我想要一个 if label = label2 在后台,用户的应用推送通知。

 label.text = myString
    if label.text! == label2.text! {

            let content = UNMutableNotificationContent()
            content.title = "\(label2.text!)Değeri Kaydedildi!"
            content.body = "Değer döndüğünde haber verilecek."
            content.sound = UNNotificationSound.default()

            let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)

            let request = UNNotificationRequest.init(identifier: "deneme", content: content, trigger: trigger)

            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

        }

【问题讨论】:

  • 对于可能遇到此问题的其他任何人..您不应该在后台进行 UI 工作。您的应用程序在后台运行后只会运行很短的时间,然后将被暂停。这意味着此代码将不会运行。您可以使用远程、静默通知来触发更新或后台获取,然后根据数据发送通知......而不是 UI

标签: ios swift usernotifications


【解决方案1】:

在AppDelegate中,尝试查找函数didReceiveRemoteNotification

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
                 fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    #if DEBUG
    print("Get User Info fetchCompletionHandler \(userInfo)")
    #endif

    // Your notification is in userInfo, you should cast it first before you show it
    // Do what you want

    completionHandler(.newData)
}

【讨论】:

  • 这是用于远程推送通知而不是本地通知。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-18
  • 1970-01-01
相关资源
最近更新 更多