How to Setup Local Notifications in iOS Xcode

Notifications are for informing user about any important activity in the App. The most important feature of notifications is that it works even when the app is in background.

There are two types of Notifications – Remote and Local. Push/Remote Notifications were introduced in iOS 3. Since the release of iOS 4, Apple introduced a new type of notification called Local Notification.

Remote notification requires a server-side program hosted somewhere, which talks to an APNS (Apple Push Notification Service). This is bit complicated and requires the user to know server-side programming.

Local notification are much simpler, you can schedule a notification with simple API and it’ll be fired up at a proper time.

Here is the code for scheduling a notification –

1
2
3
4
5
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];
localNotification.alertBody = @"Your alert message";
localNotification.timeZone = [NSTimeZone defaultTimeZone];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

In iOS 8 and later, apps that use remote or local notifications must register the types of notifications they intend to deliver.

Below is code to register for all notifications types –

1
2
3
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *mySettings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:mySettings];

The first time you call the registerUserNotificationSettings: method, iOS presents a dialog that asks the user for permission to present the types of notifications the app registered. After the user replies, iOS asynchronously calls back to the UIApplicationDelegate object with the application:didRegisterUserNotificationSettings: method.

For recurring notification, add the following line when scheduling notification –

1
localNotification.repeatInterval = NSCalendarUnitMinute;

More on NSCalendarUnit here.

You can check my sample project at GitHub.

Namit Gupta

iOS Consultant at @RapidCircle. Passionate about Mobile Apps. Loves to Design. You can reach him on his social profiles below.

Leave a Reply