简体   繁体   English

Swift 中的推送通知

[英]Push Notifications in Swift

I want to make a push notifications, but this code doesn't do what I need.我想做一个推送通知,但这段代码没有做我需要的。 Notifications are also created in place of content.body is always the same text, which is the last element in the foodsForNotifications array.通知也被创建来代替 content.body 总是相同的文本,它是 foodForNotifications 数组中的最后一个元素。 How can I fix this?我怎样才能解决这个问题?

    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
}

You keep resetting the value, the end value for every notification would be the last item in the list.您不断重置该值,每个通知的最终值将是列表中的最后一项。

You should maybe use a counter or something in this part to get a single unique value from your array for each notification.您可能应该在这部分使用计数器或其他东西从您的数组中为每个通知获取一个唯一值。

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

That probably isn't the best way to go about it, it would depend on whats in the arrays and what your goal was but it should give you a good idea of where the problem lies.这可能不是最好的方法,这取决于数组中的内容以及您的目标是什么,但它应该让您很好地了解问题所在。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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