0

NUUserNotification に移行していますが、新しいフレームワークで通知を学習していて、古いフレームワークがわからないため、問題が発生しています。移行方法に関する多くの投稿とチュートリアルを読みましたが、このケースに適用する方法を理解できるものを見つけられなかったため、これが重複していないことを願っています. 私が更新しているコードは私のものではなく、理解するのに時間がかかりました。これは、iOS アラーム ( https://github.com/natsu1211/Alarm-ios-swift ) のクローンであり、アプリに組み込んで、スケジュールされた時間/日などに実行します... 私が持っている 2 つのこと理解するのが難しいのは、通知の繰り返しです。私が理解している限り、今では毎週または1回ですよね?fireDate パラメータは減価償却されているので、これをどのように書き換えますか? :

private func minFireDateWithIndex(notifications: [UILocalNotification]) -> (Date, Int)? {
    if notifications.isEmpty {
        return nil
    }
    var minIndex = -1
    var minDate: Date = notifications.first!.fireDate!
    for n in notifications {
        let index = n.userInfo!["index"] as! Int
        if(n.fireDate! <= minDate) {
            minDate = n.fireDate!
            minIndex = index
        }
    }
    return (minDate, minIndex)
}

更新に問題がある他のコードは、現在の既存の通知のチェックですgetPendingNotificationRequestsWithCompletionHandler:]。通知を定義するのは古い関数のif let n = UIApplication.shared.scheduledLocalNotifications内部で、残りの部分を更新したと思います。古いコード:

func setupNotificationSettings() -> UIUserNotificationSettings {

        var snoozeEnabled: Bool = false

        if let n = UIApplication.shared.scheduledLocalNotifications {
            if let result = minFireDateWithIndex(notifications: n) {
                let i = result.1
                snoozeEnabled = alarmModel.alarms[i].snoozeEnabled
            }
        }

        // Specify the notification types.

        let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.sound]
        // Specify the notification actions.
        let stopAction = UIMutableUserNotificationAction()
        stopAction.identifier = Id.stopIdentifier
        stopAction.title = "OK"

        stopAction.activationMode = UIUserNotificationActivationMode.background    // choose activation mode for app on tapping notification

        stopAction.isDestructive = false
        stopAction.isAuthenticationRequired = false

        let snoozeAction = UIMutableUserNotificationAction()
        snoozeAction.identifier = Id.snoozeIdentifier
        snoozeAction.title = "Snooze"
        snoozeAction.activationMode = UIUserNotificationActivationMode.background
        snoozeAction.isDestructive = false
        snoozeAction.isAuthenticationRequired = false

        let actionsArray = snoozeEnabled ? [UIUserNotificationAction](arrayLiteral: snoozeAction, stopAction) : [UIUserNotificationAction](arrayLiteral: stopAction)
        let actionsArrayMinimal = snoozeEnabled ? [UIUserNotificationAction](arrayLiteral: snoozeAction, stopAction) : [UIUserNotificationAction](arrayLiteral: stopAction)
        // Specify the category related to the above actions.
        let alarmCategory = UIMutableUserNotificationCategory()
        alarmCategory.identifier = "myAlarmCategory"
        alarmCategory.setActions(actionsArray, for: .default)
        alarmCategory.setActions(actionsArrayMinimal, for: .minimal)


        let categoriesForSettings = Set(arrayLiteral: alarmCategory)
        // Register the notification settings.
        let newNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: categoriesForSettings)
        UIApplication.shared.registerUserNotificationSettings(newNotificationSettings)
        return newNotificationSettings
    }

新しいコード編集:

    func setRouteNotification(_ date: Date, onWeekdaysForNotify weekdays:[Int], snoozeEnabled:Bool,  onSnooze: Bool, soundName: String, routeName: String, index: Int) {
    // Notification content
    let routeCheckNotificationContent = UNMutableNotificationContent()
    let datesForNotification = correctDate(date, onWeekdaysForNotify: weekdays)
    routeCheckNotificationContent.title = "Hello!! Are you ready to cycle?"
    routeCheckNotificationContent.body = "Check route for alerts?"
    routeCheckNotificationContent.categoryIdentifier = Id.notificationCategory
    routeCheckNotificationContent.sound = UNNotificationSound.init(named: soundName + ".mp3") // check for the + ".mp3"

    // Define actions
    let check = UNNotificationAction(identifier: Id.checkActionIdentifier, title: " Check", options: [.foreground])
    let wait = UNNotificationAction(identifier: Id.waitActionIdentifier, title: "Wait", options: [])
    // Define category
    let routeCategory = UNNotificationCategory(identifier: Id.notificationCategory, actions: [check, wait], intentIdentifiers: [], options: [])
    // Register category
    UNUserNotificationCenter.current().setNotificationCategories([routeCategory])


    let repeating: Bool = !weekdays.isEmpty
    routeCheckNotificationContent.userInfo = ["snooze" : snoozeEnabled, "index": index, "soundName": soundName, "routeName": routeName, "repeating" : repeating]
    //repeat weekly if repeat weekdays are selected
    //no repeat with snooze notification
    if !weekdays.isEmpty && !onSnooze{
    }

    syncAlarmModel()
    for d in datesForNotification {
        if onSnooze {
            alarmModel.alarms[index].date = Scheduler.correctSecondComponent(date: alarmModel.alarms[index].date)
        }
        else {
            alarmModel.alarms[index].date = d
        }
        // Notification trigger

        let calendar = Calendar(identifier: .gregorian)


        let components = calendar.dateComponents(in: .current, from: d)
        let newComponents = DateComponents(calendar: calendar, timeZone: .current, month: components.month, day: components.day, hour: components.hour, minute: components.minute, second: components.second, weekday: components.weekday)
        let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)
        // Notification Request
        let routeNotificationRequest = UNNotificationRequest(identifier: "routeNotificationRequest", content: routeCheckNotificationContent, trigger: trigger)

        // Add request
        UNUserNotificationCenter.current().add(routeNotificationRequest) { (Error) in
            if Error != nil {
                print("something went wrong with adding notification")
            }
        }
    }
}

var weekdays: [Int]!行を選択して WeekdaysViewController ( a TableViewController ) に取り込まれた配列です。

任意の日を選択すると、通知が発生しなくなりました。

4

2 に答える 2