User Set Time for Notification in Swift

How do I send local notifications at a specific time in Swift?

This is an example of what I have used for scheduling local notifications using Notification Centre.

let center = UNUserNotificationCenter.current()

let content = UNMutableNotificationContent()
content.title = "My title"
content.body = "Lots of text"
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "yourIdentifier"
content.userInfo = ["example": "information"] // You can retrieve this when displaying notification

// Setup trigger time
var calendar = Calendar.current
calendar.timeZone = TimeZone.current
let testDate = Date() + 5 // Set this to whatever date you need
let trigger = UNCalendarNotificationTrigger(dateMatching: testDate, repeats: false)

// Create request
let uniqueID = UUID().uuidString // Keep a record of this if necessary
let request = UNNotificationRequest(identifier: uniqueID, content: content, trigger: trigger)
center.add(request) // Add the notification request

The Date object (represented by testDate above) can be whatever date you want. It is often convenient to create it from DateComponents.

You will need to ask permission for local notifications in the App Delegate at startup to allow this to work. Here is an example.

class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

// Ask permission for notifications
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
if granted {
print("Permission granted")
} else {
print("Permission denied\n")
}
}
}
}

How to enable iOS time-sensitive notifications switch in app settings?

I've tested it on iOS15, and if you want to send time-sensitive notifications.

  1. go to Signing&Capabilities, add Time Sensitive Notifications

enter image description here


  1. Install app to your iPhone, then allow notification, you can see Time Sensitive Notifications switch display in setting. And it's on by default

enter image description here


  1. Send Time Sensitive Notifications, set interruptionLevel to timeSensitive.
    let content = UNMutableNotificationContent()
if #available(iOS 15.0, *) {
content.interruptionLevel = .timeSensitive
}

How to get a push notification at a set time? (Swift 3)

Here is some code I used before. Not a hundred-percent what you are looking for, but I hope useful for you.

You need to modify it to be sending daily

import UIKit
import UserNotifications

class ViewController: UIViewController, UNUserNotificationCenterDelegate {
var isGrantedNotificationAccess:Bool = false
@IBAction func send10SecNotification(_ sender: UIButton) {
if isGrantedNotificationAccess {
//add notification code here

//Set the content of the notification
let content = UNMutableNotificationContent()
content.title = "10 Second Notification Demo"
content.subtitle = "From MakeAppPie.com"
content.body = "Notification after 10 seconds - Your pizza is Ready!!"

//Set the trigger of the notification -- here a timer.
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 10.0,
repeats: true)

//Set the request for the notification from the above
let request = UNNotificationRequest(
identifier: "10.second.message",
content: content,
trigger: trigger
)

//Add the notification to the currnet notification center
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

}
}

override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
self.isGrantedNotificationAccess = granted
}
}
}

Launch a local notification at a specific time in iOS

Well in iOS 10 Apple has deprecated UILocalNotification which means it is time to get familiar with a new notifications framework.

Setup
This is a long post so let’s start easy by importing the new notifications framework:

// Swift
import UserNotifications

// Objective-C (with modules enabled)
@import UserNotifications;

You manage notifications through a shared UNUserNotificationCenter object:

// Swift
let center = UNUserNotificationCenter.current()

// Objective-C
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

Authorization
As with the older notifications framework you need to have the user’s permission for the types of notification your App will use. Make the request early in your App life cycle such as in application:didFinishLaunchingWithOptions:. The first time your App requests authorization the system shows the user an alert, after that they can manage the permissions from settings:

// Swift
let options: UNAuthorizationOptions = [.alert, .sound];

// Objective-C
UNAuthorizationOptions options = UNAuthorizationOptionAlert + UNAuthorizationOptionSound;

You make the actual authorization request using the shared notification center:

// Swift
center.requestAuthorization(options: options) { (granted, error) in
if !granted {
print("Something went wrong")
}
}

// Objective-C
[center requestAuthorizationWithOptions:options
completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!granted) {
NSLog(@"Something went wrong");
}
}];

The framework calls the completion handler with a boolean indicating if the access was granted and an error object which will be nil if no error occurred.

Note: The user can change the notifications settings for your App at any time. You can check the allowed settings with getNotificationSettings. This calls a completion block asynchronously with a UNNotificationSettings object you can use to check the authorization status or the individual notification settings:

 // Swift
center.getNotificationSettings { (settings) in
if settings.authorizationStatus != .authorized {
// Notifications not allowed
}
}

// Objective-C
[center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
if (settings.authorizationStatus != UNAuthorizationStatusAuthorized) {
// Notifications not allowed
}
}];

Creating A Notification Request
A UNNotificationRequest notification request contains content and a trigger condition:

Notification Content

The content of a notification is an instance of the UNMutableNotificationContent with the following properties set as required:

title: String containing the primary reason for the alert.

subtitle: String containing an alert subtitle (if required)

body: String containing the alert message text

badge: Number to show on the app’s icon.

sound: A sound to play when the alert is delivered. Use UNNotificationSound.default() or create a custom sound from a file.
launchImageName: name of a launch image to use if your app is launched in response to a notification.

userInfo: A dictionary of custom info to pass in the notification
attachments: An array of UNNotificationAttachment objects. Use to include audio, image or video content.

Note that when localizing the alert strings like the title it is better to use localizedUserNotificationString(forKey:arguments:) which delays loading the localization until the notification is delivered.

A quick example:

 // Swift
let content = UNMutableNotificationContent()
content.title = "Don't forget"
content.body = "Buy some milk"
content.sound = UNNotificationSound.default()

// Objective-C
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Don't forget";
content.body = @"Buy some milk";
content.sound = [UNNotificationSound defaultSound];

Notification Trigger

Trigger a notification based on time, calendar or location. The trigger can be repeating:

Time interval: Schedule a notification for a number of seconds later. For example to trigger in five minutes:

 // Swift
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 300, repeats: false)

// Objective-C
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:300
repeats:NO];

Calendar: Trigger at a specific date and time. The trigger is created using a date components object which makes it easier for certain repeating intervals. To convert a Date to its date components use the current calendar. For example:

 // Swift
let date = Date(timeIntervalSinceNow: 3600)
let triggerDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)

// Objective-C
NSDate *date = [NSDate dateWithTimeIntervalSinceNow:3600];
NSDateComponents *triggerDate = [[NSCalendar currentCalendar]
components:NSCalendarUnitYear +
NSCalendarUnitMonth + NSCalendarUnitDay +
NSCalendarUnitHour + NSCalendarUnitMinute +
NSCalendarUnitSecond fromDate:date];

To create the trigger from the date components:

 // Swift
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: false)

// Objective-C
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate
repeats:NO];

To create a trigger that repeats at a certain interval use the correct set of date components. For example, to have the notification repeat daily at the same time we need just the hour, minutes and seconds:

 let triggerDaily = Calendar.current.dateComponents([hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

To have it repeat weekly at the same time we also need the weekday:

 let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute, .second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)

Scheduling

With both the content and trigger ready we create a new notification request and add it to the notification center. Each notification request requires a string identifier for future reference:

 // Swift
let identifier = "UYLLocalNotification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

center.add(request, withCompletionHandler: { (error) in
if let error = error {
// Something went wrong
}
})

// Objective-C
NSString *identifier = @"UYLLocalNotification";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger]

[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Something went wrong: %@",error);
}
}];

User set time for notification in swift

//
// ViewController.swift
// Combining Date and Time
//
// Created by Leonardo Savio Dabus on 08/12/2014.
// Copyright (c) 2014 inDabusiness.com. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

// IBOutlet goes here
@IBOutlet var myDatePicker: UIDatePicker!
@IBOutlet var mySwitch: UISwitch!

// let = whatever goes here
// var = whatever goes here
var localNotification = UILocalNotification() // You just need one
var notificationsCounter = 0

// put your functions now
func datePicker() { myDatePicker.datePickerMode = UIDatePickerMode.Date }
func datePickerDefaultDate() { myDatePicker.date = NSDate().xDays(+1) }
func notificationsOptions() {
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.repeatInterval = .CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
localNotification.alertAction = "Open App"
localNotification.alertBody = "Here is the seven o'clock notification"
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
// you may add arbitrary key-value pairs to this dictionary.
// However, the keys and values must be valid property-list types
// if any are not, an exception is raised.
// localNotification.userInfo = [NSObject : AnyObject]?
}
func toggleSwitch(){
if mySwitch.on{
localNotification.fireDate = myDatePicker.date.fireDate // combined date = picked Date + 7:00am time
} else {
localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999) // will never be fired
}
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker()
datePickerDefaultDate()
notificationsOptions()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// here is where you place your IBActions

@IBAction func switchPressed(sender: AnyObject) {
toggleSwitch()

}
}

create a new Swift Source file at your project to put your extensions

import Foundation
public extension NSDate {
func xDays(x:Int) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: x, toDate: self, options: nil)!
}
var day: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay, fromDate: self).day }
var month: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: self).month }
var year: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: self).year }
var fireDate: NSDate { return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: 7, minute: 0, second: 0, nanosecond: 0)! }
}

Set local notifications for particular days and time swift 3

To get local notifications that repeat on a certain weekday at a certain time you can use a UNCalendarNotificationTrigger:

let notification = UNMutableNotificationContent()
notification.title = "Danger Will Robinson"
notification.subtitle = "Something This Way Comes"
notification.body = "I need to tell you something, but first read this."

// add notification for Mondays at 11:00 a.m.
var dateComponents = DateComponents()
dateComponents.weekday = 2
dateComponents.hour = 11
dateComponents.minute = 0
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

If you want notifications on Monday, Thursday and Saturday at 11:00 you need to add 3 separate requests. To be able to remove them you have to keep track of the identifiers.

Setting Multiple Times for Notifications in Swift

import UIKit

class ViewController: UIViewController {

@IBOutlet var myDatePicker: UIDatePicker!
@IBOutlet var mySwitch7am: UISwitch!
@IBOutlet var mySwitch8am: UISwitch!

var localNotification7am = UILocalNotification()
var localNotification8am = UILocalNotification()
var notificationsCounter = 0

func datePicker() { myDatePicker.datePickerMode = UIDatePickerMode.Date }
func datePickerDefaultDate() { myDatePicker.date = NSDate().hour > 8 ? NSDate().xDays(+1) : NSDate() }

func notificationsOptions7am() {
localNotification7am.timeZone = NSTimeZone.localTimeZone()
localNotification7am.repeatInterval = .CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(localNotification7am)
localNotification7am.alertAction = "Open App"
localNotification7am.soundName = UILocalNotificationDefaultSoundName
}
func notificationsOptions8am() {
localNotification7am.timeZone = NSTimeZone.localTimeZone()
localNotification7am.repeatInterval = .CalendarUnitDay
UIApplication.sharedApplication().scheduleLocalNotification(localNotification8am)
localNotification7am.alertAction = "Open App"
localNotification7am.soundName = UILocalNotificationDefaultSoundName
}
func toggleSwitch7am(){
localNotification7am.alertBody = "Here is the seven o'clock notification"
localNotification7am.fireDate = mySwitch7am.on ? myDatePicker.date.fireDateAt7am : NSDate().xDays(+36500)
}
func toggleSwitch8am(){
localNotification8am.alertBody = "Here is the eight o'clock notification"
localNotification8am.fireDate = mySwitch8am.on ? myDatePicker.date.fireDateAt8am : NSDate().xDays(+36500)
}
override func viewDidLoad() {
super.viewDidLoad()
datePicker()
datePickerDefaultDate()
notificationsOptions7am()
notificationsOptions8am()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func switchedOn7am(sender: AnyObject) {
toggleSwitch7am()
}
@IBAction func switchedOn8am(sender: AnyObject) {
toggleSwitch8am()
}
}

Extensions:

    import Foundation
extension NSDate {
func xDays(x:Int) -> NSDate {
return NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitDay, value: x, toDate: self, options: nil)!
}
var day: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay, fromDate: self).day }
var month: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth, fromDate: self).month }
var year: Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear, fromDate: self).year }
var fireDateAt7am: NSDate { return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: 7, minute: 0, second: 0, nanosecond: 0)! }
var fireDateAt8am: NSDate { return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: 8, minute: 0, second: 0, nanosecond: 0)! }
func fireDateAt(hr:Int, min:Int) -> NSDate {
return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: hr, minute: min, second: 0, nanosecond: 0)!
}
}


Related Topics



Leave a reply



Submit