Два локальных уведомления планируют и показывают вместе, но у меня разное время для обоих в быстром - PullRequest
0 голосов
/ 05 октября 2018

Я реализую два локальных уведомления с разными таймингами.Эти два уведомления планируют еженедельные базы, и каждый день они будут повторяться через 1 минуту, пока пользователь не предпримет никаких действий, но проблема в том, что оба уведомления отображаются вместе, но у меня также есть разное время для обоих, я не знаю, в чем проблема .. Вотмой код

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {


    var isGrantedAccess = false
    var weekdaySet = [2,3,4,5,6,7]

    @IBOutlet weak var checkinDateLbl: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        checkinNotif()

        checkoutNotif()


        UNUserNotificationCenter.current().delegate = self
        UNUserNotificationCenter.current().requestAuthorization(
            options: [.alert,.sound,.badge],
            completionHandler: { (granted,error) in
                self.isGrantedAccess = granted
                if granted{
                    self.setCategories()
                } else {
                    let alert = UIAlertController(title: "Notification Access", message: "In order to use this application, turn on notification permissions.", preferredStyle: .alert)
                    let alertAction = UIAlertAction(title: "Okay", style: .default, handler: nil)
                    alert.addAction(alertAction)
                    self.present(alert , animated: true, completion: nil)
                }
        })
    }


    //MARK: - Functions
    func setCategories(){
        let markAttendeanceAction = UNNotificationAction(identifier: "markAttendeance", title: "Mark Attendence", options: [UNNotificationActionOptions.foreground])
        let ignoreAction = UNNotificationAction (identifier: "ignore", title: "Ignore", options: [])

        let alarmCategory1 = UNNotificationCategory(identifier: "alarm.category1",actions: [markAttendeanceAction, ignoreAction],intentIdentifiers: [], options: [])
        let alarmCategory2 = UNNotificationCategory(identifier: "alarm.category2",actions: [markAttendeanceAction, ignoreAction],intentIdentifiers: [], options: [])
        let alarmCategory3 = UNNotificationCategory(identifier: "alarm.category3",actions: [markAttendeanceAction, ignoreAction],intentIdentifiers: [], options: [])
        let alarmCategory4 = UNNotificationCategory(identifier: "alarm.category4",actions: [markAttendeanceAction, ignoreAction],intentIdentifiers: [], options: [])

        UNUserNotificationCenter.current().setNotificationCategories([alarmCategory1, alarmCategory2, alarmCategory3,alarmCategory4])

    }


    func checkinNotif(){

            let content = UNMutableNotificationContent()
            content.title = "CheckIn Alert"
            content.body = "Please Check in"
            content.sound = UNNotificationSound.default()
            content.categoryIdentifier = "alarm.category1"



            for weekday in weekdaySet {


                var datee = DateComponents()
                datee.weekday = weekday
                datee.hour = 12
                datee.minute = 34
                datee.timeZone = .current

                let triggerDate1 = UNCalendarNotificationTrigger(dateMatching: datee, repeats: true)


                let checkinNotification = UNNotificationRequest(identifier: "checkInRepeat", content: content, trigger: triggerDate1)

                UNUserNotificationCenter.current().delegate = self


                UNUserNotificationCenter.current().add(checkinNotification, withCompletionHandler: nil)
            }

            let trigger1 = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)


            let checkinReapeatNotification = UNNotificationRequest(identifier: "checkInRepeat", content: content, trigger: trigger1)

            UNUserNotificationCenter.current().add(checkinReapeatNotification, withCompletionHandler: nil)


    }


    func checkoutNotif(){
            let content1 = UNMutableNotificationContent()
            content1.title = "Checkout Alert"
            content1.body = "Please Checkout"
            content1.sound = UNNotificationSound.default()
            content1.categoryIdentifier = "alarm.category2"


            for weekday in weekdaySet {


                var datee = DateComponents()
                datee.weekday = weekday
                datee.hour = 12
                datee.minute = 37
                datee.timeZone = .current
                let triggerDate1 = UNCalendarNotificationTrigger(dateMatching: datee, repeats: true)


                let checkOutNotification = UNNotificationRequest(identifier: "checkOutRepeat", content: content1, trigger: triggerDate1)

                UNUserNotificationCenter.current().delegate = self
                UNUserNotificationCenter.current().add(checkOutNotification, withCompletionHandler: nil)
            }

            let trigger1 = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)


            let checkoutReapeatNotification = UNNotificationRequest(identifier: "checkOutRepeat", content: content1, trigger: trigger1)

            UNUserNotificationCenter.current().add(checkoutReapeatNotification, withCompletionHandler: nil)


    }
    //MARK: - Actions

    // MARK: - Delegates
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert,.sound])
    }
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {


        if response.notification.request.content.categoryIdentifier == "alarm.category1" {


            UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
                var identifiers: [String] = []
                for notification:UNNotificationRequest in notificationRequests {
                    if notification.identifier == "checkInRepeat" {
                        identifiers.append(notification.identifier)
                    }
                }
                UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)



            }

        }else if response.notification.request.content.categoryIdentifier == "alarm.category2" {
            UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in
                var identifiers: [String] = []
                for notification:UNNotificationRequest in notificationRequests {
                    if notification.identifier == "checkOutRepeat" {
                        identifiers.append(notification.identifier)
                    }
                }
                UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
            }

        }

        completionHandler()

    }


}

1 Ответ

0 голосов
/ 05 октября 2018

Когда вы добавляете UNNotificationRequest с тем же идентификатором, что и ранее существовавший, вы обновляете его, он не будет создавать новый.

В вашем коде checkinNotification и checkinReapeatNotification естьтот же идентификатор.Таким образом, единственное уведомление, которое будет отображаться, это checkinReapeatNotification, поскольку оно является последним, добавленным в центр уведомлений.То же самое касается checkOutNotification и checkoutReapeatNotification.

И поскольку вы звоните checkinNotif() и checkoutNotif() последовательно, оба checkinReapeatNotification и checkoutReapeatNotification будут запущены через 60 секунд.

Используйте withCompletionHandler в ваших интересах: при создании checkinNotification, , затем создайте checkinReapeatNotification и добавьте новое уведомление с новым идентификатором.Сделайте то же самое для checkOutNotification.

...