how to implement multiple local notification not a single notification for swift 3
Asked Answered
O

5

8

i have use the single notification , and this is my code: this is for register the local notification>>>

    func registerLocal() {
    let center = UNUserNotificationCenter.current()

    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
        if granted {
            print("Yay!")
        } else {
            print("D'oh")
        }
    }
}

and this function to schedule the local notification>>>

func scheduleLocal() {
    registerCategories()

    let center = UNUserNotificationCenter.current()

    // not required, but useful for testing!
    center.removeAllPendingNotificationRequests()

    let content = UNMutableNotificationContent()
    content.title = "good morning"
    content.body = "ttt123"
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    var dateComponents = DateComponents()
    dateComponents.hour = 23
    dateComponents.minute = 18
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

func registerCategories() {
    let center = UNUserNotificationCenter.current()
    center.delegate = self

    let show = UNNotificationAction(identifier: "show", title: "Tell me more…", options: .foreground)
    let category = UNNotificationCategory(identifier: "alarm", actions: [show], intentIdentifiers: [])

    center.setNotificationCategories([category])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // pull out the buried userInfo dictionary
    let userInfo = response.notification.request.content.userInfo

    if let customData = userInfo["customData"] as? String {
        print("Custom data received: \(customData)")

        switch response.actionIdentifier {
        case UNNotificationDefaultActionIdentifier:
            // the user swiped to unlock; do nothing
            print("Default identifier")

        case "show":
            print("Show more information…")
            break

        default:
            break
        }
    }

    // you need to call the completion handler when you're done
    completionHandler()
}

now how can i use this code with the multiple local notification with iOS 10 and different times thank you .

Olivarez answered 17/12, 2016 at 22:16 Comment(1)
So, did you find a solution for your case? :)Lownecked
T
14

Use a different request identifier for each notification (otherwise you only see the last notification). In the above example, ensure request identifier "UUID().uuidString" contains a unique value for each notification request.

Tuggle answered 6/1, 2017 at 0:1 Comment(0)
C
14

You can call the func scheduleLocal() multiple times with different dateComponents to schedule on different dates. Or you can pass a array of dates to this function and run a loop to schedule the notifications according to these dates.

Just make sure that the identifier you pass in UNNotificationRequest(identifier:, content:, trigger:) function is different for each notification.

Hope this helps. :)

Codger answered 27/1, 2017 at 11:21 Comment(1)
"Make sure to Set unique identifier for each notification" This was my mistake... +1Anastigmatic
D
2

Call this function with different parameters. Like i called when app goes background

  func applicationDidEnterBackground(_ application: UIApplication) {

        setNotification(time: 25,identifier: "notific2")
        setNotification(time: 50,identifier: "notific3")
        setNotification(time: 90,identifier: "notific4")
    }


  func setNotification (time : Int,identifier : String)
    {
        let content = UNMutableNotificationContent()
        content.title = "Don't forget"
        content.body = "Buy some milk"
        content.sound = UNNotificationSound.default()
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(time),
                                                        repeats: false)
        let center = UNUserNotificationCenter.current()
        // Swift
        let request = UNNotificationRequest(identifier: identifier,
                                            content: content, trigger: trigger)
        center.add(request, withCompletionHandler: { (error) in
            if error != nil {
                // Something went wrong
            }
        })
    }
Disrespect answered 24/5, 2017 at 8:32 Comment(0)
L
0

Note that your code should works as expected! however, there is a little pitfall.

I think that I almost faced the exact same issue, after I tried to trace the pending notifications, I noted that the only notification that has been added is the last requested one. That's because you are calling in scheduleLocal() function:

// not required, but useful for testing!
center.removeAllPendingNotificationRequests()

Well, it is good to remove any existing notification reminder requests, this would help preventing unnecessary duplicate notifications, but you should call it only once before calling scheduleLocal():

UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
// now you could call this function many times...
scheduleLocal()

simply, you don't want to delete each pending notification directly after adding it, instead you delete the whole previous pending notifications and add new ones.

Lownecked answered 17/9, 2017 at 7:56 Comment(0)
P
0

If you want to use multiple local notification than you have to used different identifier for each request.

let request = UNNotificationRequest(identifier: "Stock Changed", content: content, trigger: nil)

Change "Stock Changed" with your different identifier for each request.

You can use loop for multiple request.

Pachysandra answered 24/3, 2021 at 12:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.