iOS 10 UserNotification Framework. Calendar Trigger - swift

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.

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

Scheduling local notifications to repeat daily from tomorrow

I'm trying to schedule a local notification to fire every day, at a specific time, but from tomorrow.
e.g. "Trigger a notification every day at 2 pm, from tomorrow"
This is how I set up my schedule function.
func scheduleNotifications(date: Date, identfier: String, after: Bool) {
let content = UNMutableNotificationContent()
content.title = "App"
content.body = "Test."
content.sound = .default
content.userInfo = ["Hour": Int(hourFormatter.string(from: date)) ?? 0]
let afterDay = Calendar.current.date(byAdding: .day, value: after ? 1 : 0, to: Date())
var components = Calendar.current.dateComponents([.hour, .minute], from: afterDay!)
components.hour = Int(hourFormatter.string(from: date)) ?? 0
components.minute = Int(minuteFormatter.string(from: date)) ?? 0
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
let request = UNNotificationRequest(identifier: identfier, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)
}
This code is for daily notification just call it in tomorrow schedule time
func setupNotificationSettings() {
DispatchQueue.main.async {
let content: UNMutableNotificationContent = UNMutableNotificationContent()
content.title = AppName
content.body = "APP_Body"
content.sound = UNNotificationSound.default
let trigger: UNTimeIntervalNotificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 86400, repeats: true)
let request: UNNotificationRequest = UNNotificationRequest(identifier: "\(AppName)_Local", content: content, trigger: trigger)
let center: UNUserNotificationCenter = UNUserNotificationCenter.current()
center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
center.removeDeliveredNotifications(withIdentifiers: ["\(AppName)"])
center.add(request) { (error) in
}
}
}

How do I make multiple local notifications on Swift?

The bottom line is that I made one local notification for a time interval of 10 seconds.
How do I add multiple notifications to this code with different time delays? That is, different notifications with different delays (several hours, days, and so on).
If this is possible, please use the example of my code.
I was told that I need to put a different identifier: "content" and different times. But I don't understand what parts of the code I need to duplicate.
import UIkit
import UserNotifications
class ViewController UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Hi"
content.body = "Bear"
content.sound = UNNotificationSound.default
content.threadIdentifier = "local-notifications"
let date = Date(timeIntervalSinceNow: 10)
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: "content", content: content, trigger: trigger)
center.add(request) {(error) in
if error != nil {
print (error)
}
}
}
```
You can create method scheduleNotification(identifier:content:date:) in UNUserNotificationCenter extension ,
extension UNUserNotificationCenter {
func scheduleNotification(identifier: String, content: UNMutableNotificationContent, date: Date) {
let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
self.add(request) {(error) in
if error != nil {
print (error)
}
}
}
}
Now, call this method for multiple notifications with the appropriate parameters that you want to use, i.e.
Example-1:
let content1 = UNMutableNotificationContent()
content1.title = "Hi"
UNUserNotificationCenter.current().scheduleNotification(identifier: "content1", content: content1, date: Date(timeIntervalSinceNow: 10))
Example-2:
let content2 = UNMutableNotificationContent()
content2.title = "Hello"
UNUserNotificationCenter.current().scheduleNotification(identifier: "content2", content: content2, date: Date(timeIntervalSinceNow: 20))

How do you send a notification at a certain time that the user has entered in a text box in xcode 10?

I am trying to get a user to enter the time to take medicine or when they have an appointment in a text field and then send an alarm or notification at that time. I am a newbie so I don't know how to send notifications and such. I would need to do multiple of these depending on how many the user wants.
let content = UNMutableNotificationContent()
content.title = "Title"
content.body = "Body"
content.sound = UNNotificationSound.default()
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
// Change the time to 7:00:00 in your locale
components.hour = 7
components.minute = 0
components.second = 0
let date = gregorian.date(from: components)!
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: CommonViewController.Identifier, content: content, trigger: trigger)
print("INSIDE NOTIFICATION")
UNUserNotificationCenter.current().add(request, withCompletionHandler: {(error) in
if let error = error {
print("SOMETHING WENT WRONG")
}
})

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