Swift 中的推送通知

Push Notifications in Swift

我想发出推送通知,但这段代码无法满足我的需要。还创建通知以代替 content.body 始终是相同的文本,这是 foodsForNotifications 数组中的最后一个元素。我该如何解决这个问题?

    func scheduleLocal() {
    let center = UNUserNotificationCenter.current()

    center.removeAllPendingNotificationRequests()
    let content = UNMutableNotificationContent()

    for foods in foodForNotifications { // array for content.body
        content.body = foods
    }

    content.title = "AXAXAXAXAXAX"
    content.categoryIdentifier = "alarm"
    content.sound = UNNotificationSound.default

    for date in datesArr {  // array for date


        var dateComponents = DateComponents()

        let calendar = Calendar.current
        let dateInfo = calendar.dateComponents([.hour, .minute, .second], from: date)
        dateComponents.year = dateInfo.year
        dateComponents.month = dateInfo.month
        dateComponents.day = dateInfo.day
        dateComponents.hour = dateInfo.hour
        dateComponents.minute = dateInfo.minute
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

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

        center.add(request)
    }
}
for foods in foodForNotifications { // array for content.body
    content.body = foods
}

您不断重置该值,每个通知的结束值将是列表中的最后一项。

您应该在这部分中使用计数器或其他东西来为每个通知从您的数组中获取一个唯一的值。

var index = 0
for date in datesArr {  
     content.body = foodForNotifications[index]
     index = index + 1
}

这可能不是最好的解决方法,这取决于数组中的内容以及您的目标是什么,但它应该让您清楚地了解问题出在哪里。