Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

swift3 - Trigger notification weekly Swift 3

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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")
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...