Local notification while app not running

前端 未结 2 1079
甜味超标
甜味超标 2020-12-30 13:04

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 someth

相关标签:
2条回答
  • 2020-12-30 13:36

    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;
    }
    
    0 讨论(0)
  • 2020-12-30 13:38

    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.

    0 讨论(0)
提交回复
热议问题