设置特定日期和时间的本地通知 swift 3 [英] Set local notifications for particular days and time swift 3

查看:36
本文介绍了设置特定日期和时间的本地通知 swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我想添加本地通知.场景是用户可以选择从星期一到星期日的任何时间和日期.例如,如果用户选择周一、周四和周六作为日期,时间为晚上 11:00,那么现在应该在所有选定的日期和特定时间通知用户.

In my app, i want to add local notifications. The scenario will be that the user can select any time and days from Mon to Sun. For example, if the user selects Mon, Thur and Sat as days and time as 11:00 pm, so now the user should be notified at all the selected days and that particular time.

代码:

 let notification = UNMutableNotificationContent()
 notification.title = "Danger Will Robinson"
 notification.subtitle = "Something This Way Comes"
 notification.body = "I need to tell you something, but first read this."

 let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
 // let test = UNCalendarNotificationTrigger()
 let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
 UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

我正在使用此代码,但这不符合我的需要.

I am using this code but this doesn't work according to what I need.

推荐答案

要获取在某个工作日的某个时间重复的本地通知,您可以使用 UNCalendarNotificationTrigger:

To get local notifications that repeat on a certain weekday at a certain time you can use a UNCalendarNotificationTrigger:

let notification = UNMutableNotificationContent()
notification.title = "Danger Will Robinson"
notification.subtitle = "Something This Way Comes"
notification.body = "I need to tell you something, but first read this."

// add notification for Mondays at 11:00 a.m.
var dateComponents = DateComponents()
dateComponents.weekday = 2
dateComponents.hour = 11
dateComponents.minute = 0
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

如果您想在周一、周四和周六的 11:00 收到通知,您需要添加 3 个单独的请求.为了能够删除它们,您必须跟踪标识符.

If you want notifications on Monday, Thursday and Saturday at 11:00 you need to add 3 separate requests. To be able to remove them you have to keep track of the identifiers.

这篇关于设置特定日期和时间的本地通知 swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆