Dom*_*ams 6 ios uilocalnotification swift unnotificationtrigger
我正在尝试安排每天(在特定时间,但从明天开始)触发本地通知。
即“从明天起每天晚上8点触发通知”
我一直在使用这个 SO问题作为指导,我相信我正在按照它说的做,但是今天当我运行以下代码时(如果我将通知安排在晚上8点之前),我仍然会收到通知:
func testDateNotification(){
let content = UNMutableNotificationContent()
content.title = "Test"
content.body = "This is a test"
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())
let userCalendar = Calendar.current
var components = userCalendar.dateComponents([.hour, .minute], from: tomorrow!)
components.hour = 20
components.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if ((error) != nil){
print("Error \(String(describing: error))")
}
}
}
Run Code Online (Sandbox Code Playgroud)
import UserNotifications
检查用户权限
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
if $0 { } }
Run Code Online (Sandbox Code Playgroud)
添加通知
let fromDate = Date(timeIntervalSince1970: Double(0.0))
let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
print(trigger.nextTriggerDate() ?? "nil")
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {
if let error = $0 {
print(error)
return
}else {
print("scheduled")
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2721 次 |
| 最近记录: |