每周触发通知 Swift 3 [英] Trigger notification weekly Swift 3

查看:13
本文介绍了每周触发通知 Swift 3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制定一个时间表,其中我需要记住我上课的所有星期,例如星期一的某个时间.问题是,如果我在打印变量 triggerWeekly 时分配 weekday = 1(星期日),它会告诉我 weekday = 2,因此通过执行测试,我不会收到此类通知.我需要知道为什么会发生这种情况

I am trying to make a schedule, in which I need to remember all the weeks I have class such as Monday at certain time. The problem is that if I assign weekday = 1 (Sunday) when I print the variable triggerWeekly it tells me that weekday = 2, so by performing the tests I do not receive such notification. I need to know why this happens

let weekday = 1 //Sunday 19 Mar 
let calendar = NSCalendar.current
var date = DateComponents()
date.weekday = weekday
date.hour = 1
date.minute = 5

let ultimateDate = calendar.date(from: date)

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute], from:
ultimateDate!)

print(triggerWeekly) // hour: 1 minute: 5 second: 0 weekday: 2 isLeapMonth: false 
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let identifier = "curso(String(Index))"
let request = UNNotificationRequest(identifier: identifier,
                                        content: content, trigger: trigger)

推荐答案

您可以将触发器设置为每周一凌晨 1:05 重复,如下所示:

You can set your trigger to repeat every monday at 1:05am as follow:

import UserNotifications

let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 1, minute: 5, weekday: 2), repeats: true)
print(trigger.nextTriggerDate() ?? "nil")

let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
// make sure you give each request a unique identifier. (nextTriggerDate description)
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print(error)
        return
    }
    print("scheduled")
}

在尝试安排通知之前,不要忘记询问用户安排通知的权限:

Don't forget to ask the user permission to schedule notifications before trying to schedule your notification:

UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, error in
    if granted {
        print("authorized")
    }
}

这篇关于每周触发通知 Swift 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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