DateComponents and Notifications Not Showing - swift

I have made a to do list app. In the app, the user can select 1 of 4 buttons to set a notification. Immediate, morning, afternoon and evening. Currently, the evening and immediate work but the morning and afternoon are not working and I am unsure why.
Here is my code for the evening:
#IBAction func eveningTapped(_ sender: Any) {
eveningEnabled = true
morningEnabled = false
lockscreenEnabled = false
afternoonEnabled = false
}
if eveningEnabled == true {
var dateComponents = DateComponents()
dateComponents.hour = 18
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = taskTextField.text!
content.body = DescTextField.text!
content.sound = UNNotificationSound.default()
content.badge = 1
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if error != nil {
// Something went wrong - another alert
}
})
}
This works completely fine but the morning doesn't work, here is the code:
#IBAction func morningTapped(_ sender: Any) {
morningEnabled = true
lockscreenEnabled = false
afternoonEnabled = false
eveningEnabled = false
}
if morningEnabled == true {
var dateComponents = DateComponents()
dateComponents.hour = 07
dateComponents.minute = 00
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let content = UNMutableNotificationContent()
content.title = taskTextField.text!
content.body = DescTextField.text!
content.sound = UNNotificationSound.default()
content.badge = 1
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier,
content: content, trigger: trigger)
center.add(request, withCompletionHandler: { (error) in
if error != nil {
// Something went wrong - another alert
}
})
}

Since your code is absolutely identical (except the DateComponents) in both actions, there should be no difference when running.
But as you have a difference ('morning' is not working) the reason MUST be somewhere else (and not in the code, that you posted here). Maybe your tapAction for morning is not correctly connected in the InterfaceBuilder?
If you would post more code, we could probably better help finding the bug.
First you should check, wether your tapAction is being performed, when you tap. You can do this by adding a log command, like this:
print("Morning was tapped")
and put this code into your tapAction. Then you should get this log on your log console, after having tapped the corresponding button.

Related

Will this code send a notification on this day every month?

I have this code that should send a notification to the user on the same day every month. However I'm can't simulate this, so I can't test it. I was wondering if any of you could proof check it, to ensure it does send a notification every month.
Thanks
static func addNotification(){
let center = UNUserNotificationCenter.current()
let addRequest = {
let content = UNMutableNotificationContent()
content.title = "Test"
content.subtitle = "Test"
content.sound = UNNotificationSound.default
var dateComponents = DateComponents()
dateComponents.day = 31
dateComponents.hour = 12
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "", content: content, trigger: trigger)
center.add(request)
}
center.getNotificationSettings { settings in
if settings.authorizationStatus == .authorized{
addRequest()
}
else{
center.requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
if success{
addRequest()
}
}
}
}
}

how to set local notifications between 8am and 8pm every day

So I am very new to Swift and I'm currently setting a repeating timer every 30 min after the app was launched, but i would like to only send notification between 8 am and 8 pm. Is it possible to do this without setting a reminder for each specific time?
This is how I'm currently doing this.
override func viewDidLoad(){
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .sound]) { (granted, error ) in
// enable or disable if needed.
if granted {
print("We have permission to send notifications")
} else {
print("We don't have the option to send notifications")
}
}
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
// The actual notification the user will receive
let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: (60*30), repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
}
Unfortunately you do need to add a notification request for each 30 minute interval in the 8am-8pm window. What is your aversion to this approach? It's a simple for-loop. Instead of using a UNTimeIntervalNotificationTrigger you would use a UNCalendarNotificationTrigger.
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.removeAllDeliveredNotifications()
notificationCenter.removeAllPendingNotificationRequests()
let startHour = 8
let totalHours = 12
let totalHalfHours = totalHours * 2
for i in 0...totalHalfHours {
var date = DateComponents()
date.hour = startHour + i / 2
date.minute = 30 * (i % 2)
print("\(date.hour!):\(date.minute!)")
let notification = UNMutableNotificationContent()
notification.title = "You should have some water"
notification.body = "It has been a long time since you had some water, why don't you have some."
notification.categoryIdentifier = "reminder"
notification.sound = .default
let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
let uuidString = UUID().uuidString
let request = UNNotificationRequest(identifier: uuidString, content: notification, trigger: trigger)
notificationCenter.add(request, withCompletionHandler: nil)
}

How to make local notification repeat every day on the first of the month - swift

I'm wondering how I can make a local notification in swift repeat on the first of every month. So on the first of January, reminder. On the first of February, same reminder, and so on. Preferably using date components.
First we need to get default "UNUserNotificationCenter".
Create "UNNotificationContent".
Create the "UNCalendarNotificationTrigger".
Create "UNNotificationRequest".
Add "UNNotificationRequest" to "UNUserNotificationCenter".
let center = UNUserNotificationCenter.current()
//create the content for the notification
let content = UNMutableNotificationContent()
content.title = " Title"
content.subtitle = "SubTitle"
content.body = "jvsvsvasvbasbvfasfv"
content.sound = UNNotificationSound.default
var dateComp = DateComponents()
dateComp.month = 1;
dateComp.day = 1;
dateComp.hour = 00;
dateComp.minute = 00;
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComp, repeats: true)
//create request to display
let request = UNNotificationRequest(identifier: "ContentIdentifier", content: content, trigger: trigger)
//add request to notification center
center.add(request) { (error) in
if error != nil {
print("error \(String(describing: error))")
}
}
Use can refer this link more info.

iOS 10 UserNotification Framework. Calendar Trigger

I am on iOS 10.3.2 Beta 4 and xcode 8.3.2. I am attempting to fire a notification at the same time daily, however the notifications never seem to fire. If I do not use the calendar trigger and use the timeinterval trigger they work as expected.
Here is my code
let content = UNMutableNotificationContent()
content.title = "Daily Notification"
content.subtitle = ""
content.body = NSLocalizedString("Hello I am a notification", comment: "Comment")
content.badge = 1
content.sound = UNNotificationSound.default()
let calendar = Calendar.current
var dateComponents = calendar.dateComponents([.day, .month, .year, .hour], from: Date())
dateComponents.hour = 14
dateComponents.minute = 55
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
NSLog("Setting daily notification - \(dateComponents)")
let request = UNNotificationRequest(identifier: "dailyWarning", content: content, trigger: trigger)
center.add(request, withCompletionHandler: { error in
if error != nil {
NSLog("Error occurred")
} else {
NSLog("Request added successfully: %#", request)
}
})
Try creating your trigger like this:
var dateComponents = DateComponents()
dateComponents.hour = 14
dateComponents.minute = 55
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true) // Setting repeats to true will trigger the notification daily
For more information about why providing just the hour and minutes is sufficient see the explanation above Listing 1 in the documentation found here.

Why only my last local notification function is getting called?

I'm fairly new to swift and am trying to call multiple functions that request a local notification inside a UISwitch IBAction. I want to send a notification on a certain date - each quarter of the year on months 4, 7, 10, 1. Only the fourth quarter function is getting called. How can I get all four functions to be called? Here is my code:
// UISwitch for quarterly notifications
#IBAction func quarterlyFrequencyTapped(_ sender: UISwitch) {
if quarterlyFrequency.isOn == true {
firstQuarter(); secondQuarter(); thirdQuarter(); fourthQuarter()
print("quarterly frequency is \(quarterlyFrequency.isOn)")
} else {
removeQuarterlyNotification()
print("quaterly frequency is \(monthlyFrequency.isOn)")
}
}
// Functions for all four quarters
func firstQuarter() {
let firstQuarterContent = UNMutableNotificationContent()
firstQuarterContent.title = "First Quarter"
firstQuarterContent.subtitle = "Some string"
firstQuarterContent.body = "Some other string"
var firstQuarterDate = DateComponents()
firstQuarterDate.month = 3
firstQuarterDate.day = 11
firstQuarterDate.hour = 19
firstQuarterDate.minute = 20
let firstQuarterTrigger = UNCalendarNotificationTrigger(dateMatching: firstQuarterDate, repeats: true)
let firstQuarterRequestIdentifier = "Quarterly"
let firstQuarterRequest = UNNotificationRequest(identifier: firstQuarterRequestIdentifier, content: firstQuarterContent, trigger: firstQuarterTrigger)
UNUserNotificationCenter.current().add(firstQuarterRequest, withCompletionHandler: nil)
}
func secondQuarter() {
let secondQuarterContent = UNMutableNotificationContent()
secondQuarterContent.title = "Second Quarter"
secondQuarterContent.subtitle = "Some string"
secondQuarterContent.body = "Some other string"
var secondQuarterDate = DateComponents()
secondQuarterDate.month = 3
secondQuarterDate.day = 11
secondQuarterDate.hour = 19
secondQuarterDate.minute = 21
let secondQuarterTrigger = UNCalendarNotificationTrigger(dateMatching: secondQuarterDate, repeats: true)
let secondQuarterRequestIdentifier = "Quarterly"
let secondQuarterRequest = UNNotificationRequest(identifier: secondQuarterRequestIdentifier, content: secondQuarterContent, trigger: secondQuarterTrigger)
UNUserNotificationCenter.current().add(secondQuarterRequest, withCompletionHandler: nil)
}
func thirdQuarter() {
let thirdQuarterContent = UNMutableNotificationContent()
thirdQuarterContent.title = "Third Quarter"
thirdQuarterContent.subtitle = "Some string"
thirdQuarterContent.body = "Some other string"
var thirdQuarterDate = DateComponents()
thirdQuarterDate.month = 3
thirdQuarterDate.day = 11
thirdQuarterDate.hour = 19
thirdQuarterDate.minute = 22
let thirdQuarterTrigger = UNCalendarNotificationTrigger(dateMatching: thirdQuarterDate, repeats: true)
let thirdQuarterRequestIdentifier = "Quarterly"
let thirdQuarterRequest = UNNotificationRequest(identifier: thirdQuarterRequestIdentifier, content: thirdQuarterContent, trigger: thirdQuarterTrigger)
UNUserNotificationCenter.current().add(thirdQuarterRequest, withCompletionHandler: nil)
}
func fourthQuarter() {
let fourthQuarterContent = UNMutableNotificationContent()
fourthQuarterContent.title = "Fourth Quarter"
fourthQuarterContent.subtitle = "Some string"
fourthQuarterContent.body = "Some other string"
var fourthQuarterDate = DateComponents()
fourthQuarterDate.month = 3
fourthQuarterDate.day = 11
fourthQuarterDate.hour = 19
fourthQuarterDate.minute = 23
let fourthQuarterTrigger = UNCalendarNotificationTrigger(dateMatching: fourthQuarterDate, repeats: true)
//let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let fourthQuarterRequestIdentifier = "Quarterly"
let fourthQuarterRequest = UNNotificationRequest(identifier: fourthQuarterRequestIdentifier, content: fourthQuarterContent, trigger: fourthQuarterTrigger)
UNUserNotificationCenter.current().add(fourthQuarterRequest, withCompletionHandler: nil)
}
I think you're on +iOS10 and you're using UserNotifications framework right?
Very likely your identifiers have the same and each are UPDATING the previous notification.
The reason identifier exists is to assist you with updated a previous notification that has the same identifier. For example you send a notification to update the score from 0-0 to 0-1. And instead of having 2 notifications on the screen you now have only one.
Your fix is to use different identifiers for each.
For more see this moment for the WWDC video
UPDATE after your edit:
just as I said...all your notifications have "Quarterly" as their identifier. Give them each a separate name.
Just a little help
You can just add UUID().uuidString for identifier.
Kudos Honey