Search code examples
iosswiftuilocalnotification

How to implement multiple local notifications on specific day of weeks at different times in swift


I am trying to implement two local notifications on different days of week (1: on Wednesday 6pm, 2: on Sunday 10am) I applied many things but I am not getting any proper solution. If anyone give solution that will be very helpful, here is my last code which i applied

import UserNotifications

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

        let settings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: nil)
        UIApplication.shared.registerUserNotificationSettings(settings)

        let localNotification1 = UILocalNotification()
        localNotification1.alertBody = "Stay up-to-date"
        localNotification1.alertTitle = "New content is now available. Watch now!"
        localNotification1.timeZone = NSTimeZone.default
        localNotification1.fireDate = self.getSunday() as Date?
//        localNotification1.soundName =
        UIApplication.shared.scheduleLocalNotification(localNotification1)

        let localNotification2 = UILocalNotification()
        localNotification2.alertBody = "New videos Uploaded"
        localNotification2.alertTitle = "Dear Doctor, Stay up-to-date. Watch now!"
        localNotification2.timeZone = NSTimeZone.default
        localNotification2.fireDate = self.getWednesday() as Date?
        UIApplication.shared.scheduleLocalNotification(localNotification2)

        return true
}

func getSunday() -> NSDate? {
        let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
        let now: NSDate! = NSDate()

        let date10h = calendar.date(bySettingHour: 0, minute: 2, second: 0, of: now as Date, options: NSCalendar.Options.matchFirst)!

        return date10h as NSDate
    }

    func getWednesday() -> NSDate? {
        let calendar: NSCalendar! = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
        let now: NSDate! = NSDate()

        let date19h = calendar.date(bySettingHour: 0, minute: 3, second: 0, of: now as Date, options: NSCalendar.Options.matchFirst)!
        return date19h as NSDate
    }

Solution

  • UILocalNotification is deprecated in iOS 10. Use UNNotificationRequest instead,

    import UIKit
    import UserNotifications
    
    class ViewController: UIViewController, UNUserNotificationCenterDelegate {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //requesting for authorization
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in
                    if error == nil {
                        self.addMultipleLocalNotification()
                }
            })
        }
    
        func addMultipleLocalNotification(){
            //creating the notification content
            let content = UNMutableNotificationContent()
    
            //adding title, subtitle, body and badge
            content.title = "Notification title "
            content.subtitle = "Notification sub-title "
            content.body = "We are learning about iOS Local Notification"
            content.badge = 1
    
            var sundayDate = DateComponents()
            sundayDate.weekday = 0 // which is Sunday
            sundayDate.hour = 10
            sundayDate.minute = 00
    
            var wedDate = DateComponents()
            wedDate.weekday = 3 // which is wednesday
            wedDate.hour = 18
            wedDate.minute = 00
    
            let trigger = UNCalendarNotificationTrigger(dateMatching: sundayDate, repeats: true)
             let trigger1 = UNCalendarNotificationTrigger(dateMatching: wedDate, repeats: true)
            let request = UNNotificationRequest(identifier: "notificationName", content: content, trigger: trigger)
            let request2 = UNNotificationRequest(identifier: "notificationName2", content: content, trigger: trigger1)
    
    
            UNUserNotificationCenter.current().delegate = self
    
            //adding the notification to notification center
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
               UNUserNotificationCenter.current().add(request2, withCompletionHandler: nil)
    
            UNUserNotificationCenter.current().getPendingNotificationRequests(
            completionHandler: { (notficiations) in
                for localNotification in notficiations {
                    print(localNotification)
                }
            })
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    
            //displaying the ios local notification when app is in foreground
            completionHandler([.alert, .badge, .sound])
        }
    }