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

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

func addNotificationWithTimeIntervalTrigger(title :String){
        let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = "Subtitle"
        content.body = "Body"
        //content.badge = 1
        content.sound = UNNotificationSound.default()
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
        let reguest = UNNotificationRequest(identifier: "timeInterval", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(reguest) { (error) in
        }
    }

Здесь я просто передаю данные из моего tableView:

 func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    switch indexPath.row {
    case 0:
        UserNotificationManager.shared.addNotificationWithTimeIntervalTrigger(title:"aaa")
    default: break
    }

Мое уведомление: enter image description here

Как заставить уведомления идти по одному из массива? enter image description here

Ответы [ 3 ]

0 голосов
/ 14 сентября 2018

Этого можно достичь, используя indexPath.row, чтобы получить объект из вашей модели данных.Вы не поделились своей моделью данных, но массив - это полезный способ хранения ваших объектов для подобных ситуаций.

С некоторыми изменениями ваша пользовательская функция может выглядеть следующим образом.Теперь вы можете передать целочисленный индекс, чтобы получить правильный объект из вашей модели.

func addNotificationWithTimeIntervalTrigger(title: String, index: Int) {

    guard let thisObject = yourDataModelArray[index] as? YourObjectType else { return }

    let content = UNMutableNotificationContent()
    content.title = title // This could be taken from data model instead
    content.subtitle = thisObject.subtitle
    content.body = thisObject.body
    content.sound = UNNotificationSound.default()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)
    let reguest = UNNotificationRequest(identifier: "timeInterval", content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(reguest) { (error) in
        if let error = error {
            // Error handling
        }
    }
}

Тогда вы можете назвать его так.Оператор switch не требуется, поскольку он извлекает данные из вашей модели данных на основе indexPath.row.Обратите внимание, что вы также можете хранить заголовки в своей модели данных, что означает, что вам не нужно передавать это в качестве аргумента.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    UserNotificationManager.shared.addNotificationWithTimeIntervalTrigger(title:"Custom title", index: indexPath.row)
}
0 голосов
/ 15 сентября 2018

Попробуйте этот отдельный файл, созданный для локальных уведомлений

import Foundation
import UIKit
import UserNotifications

struct NotificationHandlerStruct {
    static var notifyTimer : Timer?
}

class LocalNotificationHandler: NSObject, UNUserNotificationCenterDelegate
{
    static var shared = LocalNotificationHandler()

    //MARK: Schedule Notification
    func scheduleNotification(Title title: String, Subtitle subtitle: String, BodyMessage body: String, AlertContent contentRx:[AnyHashable:Any]) {
        /// Remove Previous Displayed Notification in case if you need
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
        let content = UNMutableNotificationContent()
        //adding title, subtitle, body and badge
        content.title = title
        content.subtitle = subtitle
        content.sound = UNNotificationSound.default()
        content.body = body
        content.badge = 0
        content.userInfo = contentRx

        //getting the notification trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
        //getting the notification request
        let request = UNNotificationRequest(identifier: "gruveoCall", content: content, trigger: trigger)
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

         /// Comment Code below if you do not want to repeat same notification again after some interval of time
        if NotificationHandlerStruct.notifyTimer == nil {
            NotificationHandlerStruct.notifyTimer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { (timer) in
                self.sendNotification(NotificationContent: content)
            })
        }
        else{
            NotificationHandlerStruct.notifyTimer?.invalidate()
            NotificationHandlerStruct.notifyTimer = nil
        }

    }

    //MARK: Repeat Notification
    func sendNotification(NotificationContent content: UNMutableNotificationContent) {
        UNUserNotificationCenter.current().removeDeliveredNotifications(withIdentifiers: ["gruveoCall"])
        //getting the notification trigger
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
        //getting the notification request
        let request = UNNotificationRequest(identifier: "gruveoCall", content: content, trigger: trigger)
        //adding the notification to notification center
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }

    //MARK: Stop Timer
    func stopTimer() {
        if NotificationHandlerStruct.notifyTimer != nil {
            NotificationHandlerStruct.notifyTimer?.invalidate()
            NotificationHandlerStruct.notifyTimer = nil
        }
    }

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

        //displaying the ios local notification when app is in foreground
        completionHandler([.alert, .badge, .sound])
    }
}

Использование

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
     LocalNotificationHandler.shared.scheduleNotification(Title: self.providerListArray![indexPath.row], Subtitle: "My Subtitle", BodyMessage: "Some Message", AlertContent: ["aps":["data":"your Content"]])
 }
0 голосов
/ 14 сентября 2018

Убедитесь, что у каждого запланированного уведомления есть другой идентификатор, иначе новое заменит старое

let reguest = UNNotificationRequest(identifier: "timeInterval", content: content, trigger: trigger)
...