UILocalNotification helps to schedule specific notification for the user on specific date & time. As the name suggests that its handled & called from inside the application locally. So it can work without internet connection.
Its used in an application for various purpose like :
- Keeping user active into application & make sure app usage increases
- Notify for some reminders in the application
- Used as a reminder feature inside the application
- Keep highlighting for the features inside the application
- Daily usage reminder for the application
So here is the tutorial about how we can create a UILocalNotification & manage it.
Objective C :
Create new notification :
-(void)doCreateLocalNotification {
NSDate *now = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDateComponents *components = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitDay fromDate:now];
[components setHour:18];
[components setMinute:1];
[components setSecond:10];
NSDate *firedate = [calendar dateFromComponents:components];
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.fireDate = firedate;
notification.alertBody = @”Hey how are you ? Have you used application today ?”;
notification.repeatInterval = NSCalendarUnitDay;
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
Destry all local notifications :
-(void)doDestryNotification {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}
Read more: Healthy iOS Development Tips & Tricks
Swift :
Create new notification :
func doCreateReminder() {
let dateToFire = NSDate().addingTimeInterval(60*60*24*7)
let notification = UILocalNotification()
notification.fireDate = dateToFire as Date
notification.alertBody = NSLocalizedString(“localalert”, comment: “”)
let dict:NSDictionary = [“type” : “reminder”]
notification.userInfo = dict as! [String : String]
notification.repeatInterval = NSCalendar.Unit(rawValue: UInt(0))
notification.soundName = UILocalNotificationDefaultSoundName
UIApplication.shared.scheduleLocalNotification(notification)
}
Destry all local notifications :
func doDestryAllNotification() {
UIApplication.shared.applicationIconBadgeNumber = 0
UIApplication.shared.cancelAllLocalNotifications()
}