8

Is it possible to show some kind of a local notification from an app, even if the app isn't running(also not in background)?

For example a daily reminder or something like that. I know that it is possible with push-notifications, but it doesn't fit for my app.

3
  • Push notifications require payments to work. I think the best options is a background runnable thread Commented Jan 1, 2015 at 17:03
  • Well but if the user stops the app the background thread will also be killed right? Commented Jan 1, 2015 at 17:06
  • 1
    @EnriqueQuero What do you mean by payments? Commented Jan 1, 2015 at 17:27

3 Answers 3

19

You can easily schedule local notifications, and they will be presented at the scheduled date and time regardless of the app's state.

First you need to get permission from the user to present notifications, like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound|UIUserNotificationType.Alert | UIUserNotificationType.Badge, categories: nil)) return true } 

Then you create the notification like this:

var localNotification:UILocalNotification = UILocalNotification() localNotification.alertAction = "This is" localNotification.alertBody = "A notification" localNotification.fireDate = NSDate(timeIntervalSinceNow: 15) UIApplication.sharedApplication().scheduleLocalNotification(localNotification) 

Have a look at the Local and Remote Notification Programming Guide.

Sign up to request clarification or add additional context in comments.

2 Comments

This is an awesome answer and resolved my problem. Works like a charm.
UILocalNotification has been deprecated. Take a look at this Swift 3 example for local notifications with UNUserNotificationCenter.
0

In AppDelegate, use this function instead

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil) application.registerUserNotificationSettings(settings) return true; } 

Comments

0

Most of the solutions outlined above have all been deprecated. Use this UNUserNotification APIs instead

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { registerForLocalNotification() return true } func registerForLocalNotification() { UNUserNotificationCenter.current() .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, _ in print("Permission: \(granted)") } } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.