I have time picker set up. Local notification takes time from the time picker and sends the notification.
I have three notification with identifiers notfica2, notifica3 and notifica 4.
Now, I want to repeat notifica 2 and notifica3 every weekday (Monday to Friday) and repeat notifica 4 every weekend (Saturday-Sunday).
I didn't pick dates for the notificas. So I think timePicker automatically picks the date the time was set.
Please show me how to implement this specific repeat option.
Also, I have another bug. Lets say when I am picking the time it is 5 pm. And I want to set time 3 pm for notifica2 and notifica3 (which I want to repeat every weekday)
The exception says negative time. I understand the issue but I need a fix. So, if I put 3 pm but its already 6 pm then the 3pm notification will be sent the next day if it is not Saturday or Sunday. Same with notifica 4. But instead this will shift by 5 days for next Saturday.
Here is my code so far.
This is a small part of a larger app.
var textfield: UITextField!
let timePicker = UIDatePicker()
let timePicker2 = UIDatePicker()
let timePicker3 = UIDatePicker()
func timePickerFunction(){
//toolbar
timePicker.datePickerMode = UIDatePickerMode.time
timePicker2.datePickerMode = UIDatePickerMode.time
timePicker3.datePickerMode = UIDatePickerMode.time
let toolBar = UIToolbar()
toolBar.sizeToFit()
//DoneButton
let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: nil, action: #selector (donePressed))
toolBar.setItems([doneButton], animated: false)
BWTimePicker.inputAccessoryView = toolBar
AWTimePicker.inputAccessoryView = toolBar
ODTimePicker.inputAccessoryView = toolBar
//Assigning timepicker to the text fields
BWTimePicker.inputView = timePicker
AWTimePicker.inputView = timePicker2
ODTimePicker.inputView = timePicker3
}
func donePressed(){
//Formatting the date.
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .none
dateFormatter.timeStyle = .short
// BWTimePicker.text = "\(timePicker.date)"
// AWTimePicker.text = "\(timePicker.date)"
// ODTimePicker.text = "\(timePicker.date)"
// self.view.endEditing(true)
if BWTimePicker.isEditing {
//do something to textfield1
BWTimePicker.text = dateFormatter.string(from: timePicker.date)
self.view.endEditing(true)
}
else if AWTimePicker.isEditing {
//do something to textfield2
AWTimePicker.text = dateFormatter.string(from: timePicker2.date)
self.view.endEditing(true)
}
else if ODTimePicker.isEditing {
//do something to textfield2
ODTimePicker.text = dateFormatter.string(from: timePicker3.date)
self.view.endEditing(true)
}
// self.view.endEditing(true)
}
#IBAction func updateTime(_ sender: UIButton) {
//1. Get text from three UITextField objects.
let stringBW = BWTimePicker.text
let stringAW = AWTimePicker.text
let stringOD = ODTimePicker.text
//2. If the three time fields are not empty , we would send the notificaiton
if !(stringBW?.isEmpty)! && !(stringAW?.isEmpty)! && !(stringOD?.isEmpty)! {
//3. We would create a dictionary object which would be send in the notification
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hi!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Your Satisfier Quote is Ready", arguments: nil)
content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
var timeInterval1: Double = 0
var timeInterval2: Double = 0
var timeInterval3: Double = 0
let date = timePicker.date
let date2 = timePicker2.date
let date3 = timePicker3.date
timeInterval1 = date.timeIntervalSinceNow
timeInterval2 = date2.timeIntervalSinceNow
timeInterval3 = date3.timeIntervalSinceNow
print("HMMMMMMMMMKMKMKMKSMKDMSKDMSK")
print(timeInterval1)
print(timeInterval2)
print(timeInterval3)
setNotification(timeInterval:timeInterval1,identifier: "notific2", date: date)
setNotification(timeInterval:timeInterval2,identifier: "notific3", date: date2)
setNotification(timeInterval:timeInterval3,identifier: "notific4", date: date3)
self.isProfileViewVisible = true
self.extraViewTopConstraint2.constant = 1000
self.profileViewTopConstraint.constant = 150
}
else{
//2. Ask user to enter text in all the fields.
self.isProfileViewVisible = true
self.extraViewTopConstraint2.constant = 1000
self.profileViewTopConstraint.constant = 150
}
}
func setNotification (timeInterval : Double, identifier : String, date : Date){
let A: Int = 0
let B: Int = codeTwo.count
let C: Int = codeOne.count
let D: Int = codeThree.count
let number1 = Int (arc4random_uniform(UInt32(B - 1)))
let number2 = Int (arc4random_uniform(UInt32(C - 1)))
let number3 = Int (arc4random_uniform(UInt32(D - 1)))
//Repeat fundtion only added to notifica 2 for experimaental purpose/
if(identifier == "notific2"){
let content: UILocalNotification = UILocalNotification()
content.category = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.alertBody = NSString.localizedUserNotificationString(forKey: "\(codeTwo[number1])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.soundName = UILocalNotificationDefaultSoundName
let time = date
content.fireDate = time
content.repeatInterval = NSCalendar.Unit.day
// let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: time as Date)
//
// let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
// repeats: true)
//
// //let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
// let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
//
// let center = UNUserNotificationCenter.current()
// center.add(request)
UIApplication.shared.scheduleLocalNotification(content)
}
if(identifier == "notific3"){
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "\(codeThree[number3])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
}
if(identifier == "notific4"){
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hey there!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "\(codeOne[number2])", arguments: nil)
//content.categoryIdentifier = "time-test"
content.sound = UNNotificationSound.default()
let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: timeInterval, repeats: true)
let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request)
}
}
//MARK: ViewController lifeCycle
override func viewDidLoad() {
super.viewDidLoad()
self.customization()
self.collectionView.allowsMultipleSelection = true
searchBar.delegate = self
//searchBar.returnKeyType = UIReturnKeyType.done
items = items1
self.navigationController?.isNavigationBarHidden = true
timePickerFunction()
// (sender as AnyObject).setTitle("Add to Group", for: [])
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound])
{
(granted, error) in
self.notificationGranted = granted
if let error = error {
print("granted, but Error in notification permission:\(error.localizedDescription)")
}
}
}
Related
I would like to send a local notification once 24 hours has passed after a button is selected. The button is currently only enabled once 24 hours has passed and the waiting time is saved in UserDegaults. I would like to know how I will be able to send a local notification to the user automatically once the 24 hours has passed.
func getNextQuote(){
let defaults = UserDefaults.standard
defaults.integer(forKey: "savedIndexKey")
let currentIndex = defaults.integer(forKey: "savedIndexKey")
var nextIndex = currentIndex+1
nextIndex = quotes.indices.contains(nextIndex) ? nextIndex : 0
defaults.set(nextIndex, forKey: "savedIndexKey")
let savedInteger = defaults.integer(forKey: "savedIndexKey")
saved = savedInteger
quotesLabel.text = quotes[savedInteger]
self.quotesLabel.fadeIn()
set24HrTimer()
update()
}
func update(){
if let waitingDate = UserDefaults.standard.value(forKey: "waitingDate") as? Date{
if let waitingDate = UserDefaults.standard.object(forKey: "waitingDate") as? Date,
waitingDate < Date() {
self.timeLabel.text = "Please check in for the day"
self.remainingLabel.text = "Did you stay clean today?"
self.remainingLabel.font = UIFont(name: "Arial", size: 32)
self.quotesLabel.isHidden = true
addButton.isHidden = false
noButton.isHidden = false
gridButton.isHidden = false
self.view.setNeedsDisplay()
print("time is up")
}else if let waitingDate = UserDefaults.standard.value(forKey: "waitingDate") as? Date {
self.timeLabel.attributedText = self.timeLeftExtended(date: waitingDate)
addButton.isHidden = true
noButton.isHidden = true
gridButton.isHidden = true
self.quotesLabel.isHidden = false
self.remainingLabel.text = "Until next check in"
self.quotesLabel.fadeIn()
print("still running")
}else{
let newDate = Calendar.current.date(byAdding: .hour, value: 24, to: Date())
UserDefaults.standard.set(newDate, forKey: "waitingDate")
self.timeLabel.attributedText = self.timeLeftExtended(date: newDate!)
print("last option")
}
}
}
func set24HrTimer() {
let currentDate = Date()
let newDate = Date(timeInterval: 86400, since: currentDate as Date)
UserDefaults.standard.setValue(newDate, forKey: "waitingDate")
print("24 hours started")
}
func timeLeftExtended(date:Date) ->NSAttributedString{
let cal = Calendar.current
let now = Date()
let calendarUnits:NSCalendar.Unit = [NSCalendar.Unit.hour, NSCalendar.Unit.minute, NSCalendar.Unit.second]
let components = cal.dateComponents([.hour, .minute, .second], from: now, to: date)
let fullCountDownStr = "\(components.hour!)h \(components.minute!)m \(components.second!)s "
let mutableStr = NSMutableAttributedString(string: fullCountDownStr, attributes: [NSAttributedString.Key.foregroundColor:UIColor.white])
for (index, char) in mutableStr.string.enumerated()
{
if(char == "h" || char == "m" || char == "s")
{
mutableStr.removeAttribute(NSAttributedString.Key.foregroundColor, range: NSMakeRange(index, 1))
mutableStr.addAttributes([NSAttributedString.Key.foregroundColor : UIColor.lightGray], range: NSMakeRange(index, 1))
}
}
return mutableStr
}
func setupTimer()
{
if(!timeWorking)
{
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.updateCountDown), userInfo: nil, repeats: true)
self.timeWorking = true
}
}
You shouldn't use a timer to trigger a local notification. This function could be added as an extension to UIViewController that will let you create a UNCalendarNotificationTrigger:
import UserNotifications
import UIKit
extension UIViewController {
func createLocalNotification(title: String, hours: Int) {
let seconds = hours * 3600
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default
content.title = title
let nextTriggerDate = Calendar.current.date(byAdding: .second, value: seconds, to: Date())!
let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: nextTriggerDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
let request = UNNotificationRequest(identifier: "\(seconds)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
}
And can be used within your UIViewController as follows:
let MyViewController: UIViewController {
#IBAction func buttonPressed(_ sender: Any) {
self.createLocalNotification(title: "24 hours have passed!", hours: 24)
}
}
I want to schedule a notification to be fired twice a week:
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
[2, 4].forEach { day in
let content = UNMutableNotificationContent()
content.title = "Notif title"
content.body = "Comment"
content.sound = .default
var components = gregorian.dateComponents([.year, .month, .weekdayOrdinal, .day, .hour, .minute, .second], from: now)
components.hour = 11
components.minute = 25
components.second = 0
components.weekdayOrdinal = day
let date = gregorian.date(from: components)!
let triggerDaily = gregorian.dateComponents([.weekdayOrdinal, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Oops: \(error)")
} else {
print("Notification created!")
}
}
}
But instead of being fired once on monday and once on wednesday, it gets called two times each day.
What am I doing wrong? Thanks for your help.
because of foreach loop your code schedule two notification with the same identifier. while your code is getting execute the 2nd loop cycle overwrite the request.
I did some R&D and refine your code a bit. On my side, it works perfectly.
Please try the code mention below.
func setNotification() {
let days = [2,4]
func ScheduleNotification(index:Int){
let calendarComponents = NSDateComponents()
calendarComponents.hour = 11
calendarComponents.minute = 25
calendarComponents.second = 0
calendarComponents.weekday = days[index]
let content = UNMutableNotificationContent()
content.title = "Notification title"
content.body = "your message here."
content.sound = UNNotificationSound.default
let trigger = UNCalendarNotificationTrigger(dateMatching: calendarComponents as DateComponents, repeats: true)
let identifier = "UYLLocalNotification\(days[index])"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
if let error = error {
print(error)
}else{
if index == 0{
ScheduleNotification(index: 1)
}
}
})
}
ScheduleNotification(index: 0)
}
call this function in your viewdidLoad method like.
self.setNotification()
i hope it will save your time.
Simply change the name of identifier of each notification inside the foreach(_:) to something like test2, test4, i.e.
[2, 4].forEach {
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
content.sound = .default
var components = DateComponents()
components.timeZone = TimeZone.current
components.weekday = 11
components.hour = 25
components.minute = 0
components.second = $0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: "test\($0)", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
if let error = error {
print("Oops: \(error)")
} else {
print("Notification created!")
}
}
}
You can use .weekday instead of .weekdayOrdinal . According to Apple document
.weekday = A weekday or count of weekdays.
.weekdayOrdinal = weekday ordinal or count of weekday ordinals.
Weekday ordinal units represent the position of the weekday within the
next larger calendar unit, such as the month. For example, 2 is the
weekday ordinal unit for the second Friday of the month.
Try this
let triggerDate = Calendar.current.dateComponents([.weekday,.hour,.minute], from: date as Date)
triggerDat.weekday = day[index]
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
repeats: true)
I want to trigger a weekly notification that goes on Mondays at 7:00pm.
I see code like this:
let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
What should I set the from date as?
Also does the date need to be in the present?
I am using iOS 10+ and swift 3.
Pass date which you want to generate local notification
let strDate = (data as AnyObject).value(forKey: "not_date") as? String
let dateformatter = DateFormatter()
dateformatter.dateFormat = "yyyy-MM-dd hh:mm a"
let notidate = dateformatter.date(from: strDate!)
you need to first stattnotificationdate like = 2018-06-25 07:00 PM after you need to add time interval
var dateStart = Date()
dateStart = dateStart.addingTimeInterval(TimeInterval(604800))
and generate notification with these interwal
//MARK:- Schedule Notification with Daily bases.
func scheduleNotification(at date: Date, body: String, titles:String) {
let triggerDaily = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
if #available(iOS 10.0, *) {
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "HardikBar"
let request = UNNotificationRequest(identifier: "NotificationAt-\(date))", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
} else {
// Fallback on earlier versions
}
}
I have used below extension for Date:
extension Date {
static func today() -> Date {
return Date()
}
func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.Next,
weekday,
considerToday: considerToday)
}
func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {
return get(.Previous,
weekday,
considerToday: considerToday)
}
func get(_ direction: SearchDirection,
_ weekDay: Weekday,
considerToday consider: Bool = false) -> Date {
let dayName = weekDay.rawValue
let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }
assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")
let searchWeekdayIndex = weekdaysName.index(of: dayName)! + 1
let calendar = Calendar(identifier: .gregorian)
if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {
return self
}
var nextDateComponent = DateComponents()
nextDateComponent.weekday = searchWeekdayIndex
let date = calendar.nextDate(after: self,
matching: nextDateComponent,
matchingPolicy: .nextTime,
direction: direction.calendarSearchDirection)
return date!
}
}
This can be used for getting any next or previous weekday from the reference date. You'll need to get the next Monday first and then set the UNCalendarNotificationTrigger as below:
var triggerDaily = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date().next(Date.Weekday.monday, considerToday: true))
triggerDaily.hour = 19
triggerDaily.minute = 0
triggerDaily.second = 0
if #available(iOS 10.0, *) {
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "Test"
let request = UNNotificationRequest(identifier: "NotificationAt-\(String(describing: Calendar.current.date(from: triggerDaily))))", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}else {
UNUserNotificationCenter.current().getPendingNotificationRequests(completionHandler: { (arrayRequests) in
for request in arrayRequests {
if let calendarNotificationTrigger = request.trigger as? UNCalendarNotificationTrigger,
let nextTriggerDate = calendarNotificationTrigger.nextTriggerDate() {
print("nextTriggerDate ===>>> \(nextTriggerDate)")
}
print("Request ===>>> \(String(describing: request.trigger))")
}
})
}
}
} else {
// Fallback on earlier versions
}
The Output of this will be as below:
nextTriggerDate ===>>> 2018-07-02 13:30:00 +0000
Request ===>>> Optional(
Calendar Year: 2018
Month: 7
Day: 2
Hour: 19
Minute: 0
Second: 0, repeats: YES>)
You can set weekday and time in DateComponents you can receive notification for every monday at 7:00 PM and also set Repeat = "true"
func setupNotificationReminder() {
let title:String = "Your reminder text goes here"
var calendarComponents = DateComponents()
calendarComponents.weekday = 2
calendarComponents.hour = 19
calendarComponents.second = 0
calendarComponents.minute = 0
// create a corresponding local notification
let trigger = UNCalendarNotificationTrigger(dateMatching: calendarComponents, repeats: true)
let content = UNMutableNotificationContent()
content.title = title
content.body = "body"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "YourApp"
let request = UNNotificationRequest(identifier: "NotificationAtGivenTime", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
Another overload of trigger required TimeInterval
So you can get
let timeInterval = dateOfNotification.timeIntervalSinceNow
Now
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterval, repeats: true)
You can create date as
if let date = Calendar.current.date(byAdding: .day, value: 7, to: self) {
let date1 = Calendar.current.date(bySettingHour: hours, minute: minutes, second: 00, of: date)
}
If you want specific day then refer https://stackoverflow.com/a/49561764/4601900
I am trying to schedule local notifications for specific days of week (e.g. Monday, Wednesday and etc) and then repeat them weekly.
This is how the screen for setting notifications looks:
User can select time for the notification and repeating days.
My method for scheduling single non repeating notification looks like this:
static func scheduleNotification(reminder: Reminder) {
// Setup notification content.
let content = UNMutableNotificationContent()
//content.title = NSString.localizedUserNotificationString(forKey: "Reminder", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: reminder.reminderMessage, arguments: nil)
content.sound = UNNotificationSound.default()
// Configure the triger for specified time.
//
let dateComponentes = reminder.dateComponents
// TODO: Configure repeating alarm
// For the testing purposes we will not repeat the reminder
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponentes, repeats: false)
// Create the request object.
let request = UNNotificationRequest(identifier: "\(reminder.reminderId)", content: content, trigger: trigger)
// Schedule the request.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.add(request) { (error: Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
The date components are extracted from UIDatePicker widget and stored in reminder class:
let date = reminderTimeDatePicker.date.addingTimeInterval(60 * 60 * 24 * 7)
let components = Calendar.current.dateComponents([.weekday, .hour, .minute], from: date)
...
reminder.dateComponents = components
I have an array selectedDays[Int] (as a property of reminder class) to hold info on days of week on which the notification should fire.
How can I schedule notification on specific day of week and how to repeat it weekly?
Even a single comment will be helpful, and thank you in advance.
You can use below function to get Date from selected picker value:
//Create Date from picker selected value.
func createDate(weekday: Int, hour: Int, minute: Int, year: Int)->Date{
var components = DateComponents()
components.hour = hour
components.minute = minute
components.year = year
components.weekday = weekday // sunday = 1 ... saturday = 7
components.weekdayOrdinal = 10
components.timeZone = .current
let calendar = Calendar(identifier: .gregorian)
return calendar.date(from: components)!
}
//Schedule Notification with weekly bases.
func scheduleNotification(at date: Date, body: String, titles:String) {
let triggerWeekly = Calendar.current.dateComponents([.weekday,.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let content = UNMutableNotificationContent()
content.title = titles
content.body = body
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
//UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print("Uh oh! We had an error: \(error)")
}
}
}
After getting a value from picker pass picker hour, minute and year with selected week day as (Sunday = 1, Monday = 2, Tuesday = 3, Wednesday = 4, thursday = 5, Friday = 6, Saturday = 7) to function func createDate(weekday: Int, hour: Int, minute: Int, year: Int) to get notification fire date on weekly bases, and after getting date call function func scheduleNotification(at date: Date, body: String, titles:String) for schedule a notification.
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Wake up!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Rise and shine! It's morning time!",
arguments: nil)
content.categoryIdentifier = "TIMER_EXPIRED"
let weekdaySet = [6,5]
for i in weekdaySet {
var dateInfo = DateComponents()
dateInfo.hour = 16
dateInfo.minute = 44
dateInfo.weekday = i
dateInfo.timeZone = .current
let trigger = UNCalendarNotificationTrigger(dateMatching: dateInfo, repeats: true)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
center.add(request) { (error : Error?) in
if let theError = error {
print(theError.localizedDescription)
}
}
}
I want my app to notify the user everyday at 13pm. I put this inside my app delegate:
func Notification() {
var Notification = UILocalNotification()
Notification.alertAction = "New Question!"
Notification.alertBody = "Solve the new question!"
Notification.fireDate = NSDate(timeIntervalSinceNow: 0)
UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}
and this inside my application didFinishLaunching:
application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge | UIUserNotificationType.Sound, categories: nil))
What do I have to do so that my notification is scheduled to fire daily?
just set any past date that at 13pm,
and set repeatInterval as .CalendarUnitDay
let startDate = Date()
var component = Calendar.current.dateComponents([.year, .month, .day, .hour], from: Date())
component.hour = 13
let fireDate = Calendar.current.date(from: component)
notification.repeatInterval = .day;
notification.fireDate = fireDate
Update:
let trigger = UNCalendarNotificationTrigger(dateMatching: component, repeats: true)
var triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second], from: Date())
triggerDaily.hour = 13
triggerDaily.minute = 0
triggerDaily.second = 0
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
content.categoryIdentifier = "todoList"
let request = UNNotificationRequest(identifier: "identifier", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) {(error) in // to do }