2

I'm trying to make a push notifications which works when app moves to background (user press home button) using timer. Here is my code:

override func viewDidLoad() {
    super.viewDidLoad()
    UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert,.sound,.badge],
            completionHandler: nil);

    let notificationCenter = NotificationCenter.default
    notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: Notification.Name.UIApplicationWillResignActive, object: nil)     
}

var timer: Timer = Timer()

func appMovedToBackground() {
     timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(observeUnreadedMsgs), userInfo: nil, repeats: true)
}

func observeUnreadedMsgs() {
     let ref = FIRDatabase.database().reference().child("chats")
       //... some code which gets new message in chat        
     self.sendNotification(userName: userName, msgText: msg)
      // ...

}

func sendNotification(userName: String, msgText: String) {

     let content = UNMutableNotificationContent()
     content.title = userName
     content.subtitle = ""
     content.body = msgText

            //Set the trigger of the notification -- here a timer.
     let trigger = UNTimeIntervalNotificationTrigger(
     timeInterval: 5.0,
     repeats: false)

            //Set the request for the notification from the above
     let request = UNNotificationRequest(
        identifier: msgText,
         content: content,
         trigger: trigger
      )

            //Add the notification to the currnet notification center
      UNUserNotificationCenter.current().add(
                request, withCompletionHandler: nil)
}

But this code returns me only 1 push notification, and don't performs any more. Where I'm mistaking?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
coldembrace
  • 549
  • 8
  • 19
  • yep, I've changed identifier to msgText + String(NSDate().timeIntervalSince1970 * 1000) and it works correct, thx! – coldembrace Sep 13 '17 at 18:46

0 Answers0