简体   繁体   中英

Local Notification for specific date and time is not working. Swift

I am trying to trigger a local notification on a specific date and time on button click but it's not working. Below is the code:

@IBAction func setReminderBtnPressed (_ sender: UIButton) {
    var dateString = String()
    dateString = "2018-10-20 18:11:00"
    //let date = Date(timeIntervalSinceNow: 60) //Working Fine
    let date = globalMethods.convertStringToDate(dateStr: dateString) //log 2018-10-20 10:11:00 +0000 
    let content = UNMutableNotificationContent()
    content.title = "Don't forget"
    content.body = "Buy some milk"
    content.sound = UNNotificationSound.default()
    let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date) //log ▿ year: 2018 month: 10 day: 20 hour: 18 minute: 11 second: 0 isLeapMonth: false
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
        if let error = error {
            // Something went wrong
            print(error)
        }
    })
}

func convertStringToDate(dateStr: String) -> Date {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    dateFormatter.timeZone = TimeZone.current// (abbreviation: "GMT+0:00")
    let dateFromString = dateFormatter.date(from: dateStr)
    print("dateFromString: ", dateFromString!)
    return dateFromString!
}

Thanks in advance.

Make sure that you have authorized the app to send notifications to the user.

In your AppDelegate 's application(_:didFinishLaunchingWithOptions:) , request for the authorization:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { (success, error) in
    if let error = error {
        debugPrint("Error: \(error)")
    }
}
UNUserNotificationCenter.current().delegate = self

And, confirm to UNUserNotificationCenterDelegate in your AppDelegate , and implement the method:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    completionHandler(.alert)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM