How to Create Local Notifications

Sending local notifications in SWIFT

The notification comes but when the app is foreground it won't show until you implement UNUserNotificationCenterDelegate method

UNUserNotificationCenter.current().delegate = self


func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound,.alert])
}

Also set

 let date = Date().addingTimeInterval(5)

to give it some time until app hits so you can test it after clicking home button

import UIKit

class ViewController: UIViewController , UNUserNotificationCenterDelegate {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.


let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.badge,.sound,.alert]) { granted, error in
if error == nil {
print("User permission is granted : \(granted)")
}
}
// Step-2 Create the notification content
let content = UNMutableNotificationContent()
content.title = "Hello"
content.body = "Welcome"


// Step-3 Create the notification trigger
let date = Date().addingTimeInterval(5)
let dateComponent = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: false)



// Step-4 Create a request
let uuid = UUID().uuidString
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: trigger)


// Step-5 Register with Notification Center
center.add(request) { error in


}
}

func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound,.alert])
}

}

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

Local notification not firing when multiple days set

The id for each notification in the loop has to be unique.

You are using the same id for all the notifications. The newest overrides the previous.

Add something unique to the id String at the end, like the index or another UUID or the day description.



Related Topics



Leave a reply



Submit