Amish Shabani
Amish Shabani

Reputation: 759

Local notification in swift 3 with new UI

I know to how to create local notification in Swift 3( I am new in this part), However, I want to create something like below image. All tutorials in the web are too old and I do not what should I do.

Local notification

As you can see before extending notification , there are 2 buttons. after extending also there are 2 buttons with red and blue color.

Updated

Thanks Joern

The slide gesture only show clear. Is there any settings for showing both clear and view

enter image description here

Upvotes: 0

Views: 842

Answers (1)

joern
joern

Reputation: 27620

The red and blue buttons are only available in iOS versions prior to iOS 10. With iOS 10 the notifications design changed. The slide gesture is used for the standard actions Clear and View. The custom actions Snooze and Confirm will be displayed when you force touch the notification or pull it down (for devices without force touch). If you are using a device with force touch the View button might not be shown.

The buttons look different now:

enter image description here

So, here is how you implement Local Notifications with Swift 3 / 4:

For iOS versions prior to iOS 10:

If you are supporting iOS versions prior to iOS10 you have to use the old (deprecated with iOS 10) UILocalNotification:

class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        registerLocalNotification()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        scheduleLocalNotification()
    }

    func scheduleLocalNotification() {
        let localNotification = UILocalNotification()
        localNotification.alertTitle = "Buy milk"
        localNotification.alertBody = "Remember to buy milk from store"
        localNotification.fireDate = Date(timeIntervalSinceNow: 3)
        localNotification.soundName = UILocalNotificationDefaultSoundName
        localNotification.category = "reminderCategory" // Category to use the specified actions
        UIApplication.shared.scheduleLocalNotification(localNotification) // Scheduling the notification.
    }

    func registerLocalNotification() {
        let reminderActionConfirm = UIMutableUserNotificationAction()
        reminderActionConfirm.identifier = "Confirm"
        reminderActionConfirm.title = "Confirm"
        reminderActionConfirm.activationMode = .background
        reminderActionConfirm.isDestructive = false
        reminderActionConfirm.isAuthenticationRequired = false

        let reminderActionSnooze = UIMutableUserNotificationAction()
        reminderActionSnooze.identifier = "Snooze"
        reminderActionSnooze.title = "Snooze"
        reminderActionSnooze.activationMode = .background
        reminderActionSnooze.isDestructive = true
        reminderActionSnooze.isAuthenticationRequired = false

        // Create a category with the above actions
        let shoppingListReminderCategory = UIMutableUserNotificationCategory()
        shoppingListReminderCategory.identifier = "reminderCategory"
        shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .default)
        shoppingListReminderCategory.setActions([reminderActionConfirm, reminderActionSnooze], for: .minimal)

        // Register for notification: This will prompt for the user's consent to receive notifications from this app.
        let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound, .badge], categories: [shoppingListReminderCategory])

        UIApplication.shared.registerUserNotificationSettings(notificationSettings)
    }
}

This will register the local notification and fires it 3 seconds after the user closes the app (for testing purposes)

For iOS 10 and later:

If you target your app to iOS 10 you can use the new UserNotifications framework:

import UIKit
import UserNotifications

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {
        registerUserNotifications()
        return true
    }

    func applicationWillResignActive(_ application: UIApplication) {
        scheduleLocalNotification()
    }

    func registerUserNotifications() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
            guard granted else { return }
            self.setNotificationCategories()
        }
    }

    func setNotificationCategories() {
        // Create the custom actions
        let snoozeAction = UNNotificationAction(identifier: "SNOOZE_ACTION",
                                                title: "Snooze",
                                                options: .destructive)
        let confirmAction = UNNotificationAction(identifier: "CONFIRM_ACTION",
                                              title: "Confirm",
                                              options: [])

        let expiredCategory = UNNotificationCategory(identifier: "TIMER_EXPIRED",
                                                     actions: [snoozeAction, confirmAction],
                                                     intentIdentifiers: [],
                                                     options: UNNotificationCategoryOptions(rawValue: 0))

        // Register the category.
        let center = UNUserNotificationCenter.current()
        center.setNotificationCategories([expiredCategory])
    }

    func scheduleLocalNotification() {
        let content = UNMutableNotificationContent()
        content.title = "Buy milk!"
        content.body = "Remember to buy milk from store!"
        content.categoryIdentifier = "TIMER_EXPIRED"

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 3, repeats: false)

        // Create the request object.
        let request = UNNotificationRequest(identifier: "Milk reminder", content: content, trigger: trigger)

        // Schedule the request.
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error : Error?) in
            if let theError = error {
                print(theError.localizedDescription)
            }
        }
    }
}

You can check out a demo app that uses the UserNotifications framework here

Upvotes: 1

Related Questions