Schedule & reschedule local notification

This tutorial has been updated for X code 7.3 & swift 2.2

Local notifications are very important part of app. Its intended use is only for reminders set by user. But many apps set local notification programatically. They use local notification to increase interaction with the app itself. There are over million apps in App store & new apps are coming everyday. So people download the app but in couple of days completely forget about it.

If you use local notification properly then you can increase engagement with your app. If you annoy the user with excessive notification then user will disable notification or worse delete your app. Today I am going to show you how to set local notification.

  1. First lets set up the x code project as usual. Create new single view application X code project. Set project name to schedule local notification & save it on desktop.

new x code project

2. Go to main storyboard and select view controller. Set its size iPhone 4-inch in attribute section.

set size to iPhone 4 inch

3. Add date picker at bottom of view controller, add textfield with width 200 and add button as follows.

add datepicker button text field

4. Connect text field as outlet to view controller swift file

textfield to swift file

5. Connect button as outlet to view controller swift file

button to swift file

6. Connect date picker as outlet to view controller swift file

date picker to swift file

7. Go to app delegate swift file and add following code in did finish launching with option to enable local notification

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// 7
let notificationSettings = UIUserNotificationSettings(forTypes: [UIUserNotificationType.Alert, UIUserNotificationType.Badge], categories: nil)

application.registerUserNotificationSettings(notificationSettings)

return true

}

Here I am using only alert notification & badge notification. Depending on urgency for the notification & frequency of the notification you can use Sound notification also. If you have frequent sound notification of low priority then user will uninstall your app. So use sound notification sparingly.

8. The above code will ask user for permission to send local notification on first run. If the user denies permission then local notification will not receive any notification. In this case you also want to hide the UI used for saving local notification. Because it serves no purpose. Open view controller swift file & create following method.

// 8
func updateUI() {
    let currentSettings = UIApplication.sharedApplication().currentUserNotificationSettings()

    if currentSettings?.types != nil {

        if currentSettings!.types == [UIUserNotificationType.Badge, UIUserNotificationType.Alert] {

            textField.hidden = false

            button.hidden = false

            datePicker.hidden = false

        }
        else if currentSettings!.types == UIUserNotificationType.Badge {

            textField.hidden = true

        }
        else if currentSettings!.types == UIUserNotificationType.None {

            textField.hidden = true

            button.hidden = true

            datePicker.hidden = true

        }

    }

}

In first case we check if both badge & alert notification is active then display all the UI. If user disables alert notification then we hide the textfield. And if user had denied permission or closed notification then hide all of the UI.

9. In view did load of view controller swift file add newly created method as follows

override func viewDidLoad() {
super.viewDidLoad()
// 9
updateUI()

// Do any additional setup after loading the view, typically from a nib.

}

10. Go back to app delegate swift file and add following method

// 10
 func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
let viewController = self.window!.rootViewController as! ViewController

viewController.updateUI()

}

This did register user notification settings method executes after user has set notification permission. I am just going to view controller & updating the UI.

11. Before we save local notification lets test if everything is working so far. Run the app in iPhone 5s

Screen Shot 2015-10-18 at 9.53.33 PM

As you can see from the image above that at its initial state no notification is active. Hence behind the permission alert you will not see any UI visible. And if you say OK then UI will become visible as follows

Screen Shot 2015-10-18 at 9.54.03 PM

Go to Settings->schedule local notification and disable alert notification as follows

Screen Shot 2015-10-18 at 10.09.24 PM

Now run app again in iPhone 5s and you will see that textfield is now not visible

Screen Shot 2015-10-18 at 10.12.17 PM

Now disable all notifications as follows

Screen Shot 2015-10-18 at 10.12.53 PM

When you run the app in iPhone 5s you will not see any UI because its all hidden.

Screen Shot 2015-10-18 at 10.13.25 PM

12. Connect button as action to view controller swift file

schedule button to swift file

13. Add following code in button action

@IBAction func savePressed(sender: UIButton) {
// 1
let notification = UILocalNotification()
// 2
notification.fireDate = datePicker.date
// 3
if textField.text == “” {

    notification.alertBody = "New blog is posted at blog.apoorvmote.com"

}
else {

    notification.alertBody = textField.text

}
// 4
notification.timeZone = NSTimeZone.defaultTimeZone()
// 5
notification.repeatInterval = NSCalendarUnit.Minute
// 6
notification.applicationIconBadgeNumber = 1
// 7
UIApplication.sharedApplication().scheduleLocalNotification(notification)

} 
  1. Create local notification
  2. Set fire date for notification from the date picker value
  3. If the text field is empty then set default text for alert text. And if the text field is not empty then use that text.
  4. Set time zone for notification as default time zone for app. This default time zone can be different for each app. If you don’t set default time zone for the app then it takes system time zone.
  5. This is optional. But if you want to repeat local notification at specific interval then you can set it here.
  6. This sets badge number. It has to be pre calculated. You cannot change number on the fly. You can pre calculate using either number of unfinished tasks or number of notifications.
  7. Save this local notification

14. If you test the app using current settings then you would find that notification doesn’t fire exactly on time. For example if you set it to 2:05 PM then it may fire at 2:05:45 PM. Here we are going to set the value of second to zero so it fires at exact time. Create following method

// 14
func fixedNotificationDate(dateToFix: NSDate) -> NSDate {
let dateComponents: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)

dateComponents.second = 0

let fixedDate: NSDate = NSCalendar.currentCalendar().dateFromComponents(dateComponents)!

return fixedDate

}

15. Now update notification fire date from newly created method as follows

@IBAction func savePressed(sender: UIButton) {
// 1
let notification = UILocalNotification()
// 15
notification.fireDate = fixedNotificationDate(datePicker.date)

16. When you click on notification and open app or just open app when you see badge number then you want to reset badge number to zero. Open app delegate and add following code in did finish launching with options method

application.registerUserNotificationSettings(notificationSettings)
// 16
application.applicationIconBadgeNumber = 0

return true

}

17. If you receive local notification while using the app then you want to again set badge number to zero. Add following method in app delegate

// 17
func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {
application.applicationIconBadgeNumber = 0
}

18. Now run the app in iPhone 5s and see if you receive any local notification.

Screen Shot 2015-10-19 at 12.19.01 AM
Download X code file
Challenge 1: Cancel local notification at specific time.

Challenge 2: Print all local notification and cancel all local notification

Screen Shot 2015-10-19 at 12.20.37 AM
Download Challenge Solution

Total 4 Votes
0

Tell us how can I improve this tutorial?

+ = Verify Human or Spambot ?