Daily local notification worked for one day and than stopped [Swift]

78 Views Asked by At

I wrote a code for a daily local notification on my app that will be sent every day at 1:00 pm (13:00). The day I wrote it, the code worked fine and the notification sent exactly at 1:00 pm. For an unknown reason it worked great only than but now it doesn't work, I don't get any notification.

(I wrote the code inside the Signup page of the app)

The code:

import UIKit
import FirebaseAuth
import Firebase

class SignUp: UIViewController {

    @IBOutlet weak var emailSignupTF: UITextField!
    @IBOutlet weak var passwordSignupTF: UITextField!
    @IBOutlet weak var errorLabel: UILabel!
    var message = ""

    override func viewDidLoad() {
        super.viewDidLoad()        
        navigationItem.setHidesBackButton(true, animated: true)

        //First Notification//
        let content = UNMutableNotificationContent()
        content.title = "תזכורת"
        content.body = "לא לשכוח לעדכן את מיקומך בתדריך הקרוב"

        // Configure the recurring date.
        var dateComponents = DateComponents()
        dateComponents.calendar = Calendar.current
        dateComponents.hour = 13
        dateComponents.minute = 0


        // Create the trigger as a repeating event.
        let trigger = UNCalendarNotificationTrigger(
                 dateMatching: dateComponents, repeats: true)

        // Create the request
        let uuidString = UUID().uuidString
        let request = UNNotificationRequest(identifier: uuidString,
                    content: content, trigger: trigger)

        // Schedule the request with the system.
        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.add(request) { (error) in
           if error != nil {
              // Handle any errors.
           }
        }
}
1

There are 1 best solutions below

2
On

The problem here is that you are specifically taking todays date by saying dateComponents.calendar = Calendar.current and then setting an hour and minute value. This means that the notification will be sent every year, on this date at the hour and minutes specified. To fix this, simply do:

// Configure the recurring date.
var dateComponents = DateComponents()
dateComponents.hour = 13
dateComponents.minute = 0

Now the notification will be sent every day, at 13:00. Reference: https://developer.apple.com/documentation/usernotifications/uncalendarnotificationtrigger