首页 > 解决方案 > 后台运行的应用程序发送本地通知

问题描述

应用程序在后台运行时如何发送本地通知?在 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)

        }

标签: iosswiftusernotifications

解决方案


在 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)
}

推荐阅读