0

How can i send Local Notifications while app is running in the background? in Swift 4. My app continuously use an Json file and I want the app to continue running so that it sends the user a Local Notification. I want a if label = label2 in background, App push notification for user.

 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)

        }
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Holofacts
  • 1
  • 4
  • Follow this post:https://stackoverflow.com/a/53557313/3420996 – Natarajan Dec 03 '18 at 11:16
  • For anyone else that might land on this question.. you shouldn't be doing UI work in the background. Your app will only run for a short time after being backgrounded and will then get suspended. Meaning this code will not run. You can either use remote,silent notifications to trigger updates or background fetch, Then send a notification based on the data... not the UI – Scriptable Jul 22 '19 at 12:54

1 Answers1

-3

in AppDelegate, try to find function 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)
}