Creating Local Notification

Discussion in 'iOS Programming' started by Karamelli, Aug 8, 2017.

  1. Karamelli, Aug 8, 2017
    Last edited by a moderator: Aug 8, 2017

    Karamelli macrumors newbie

    Jul 29, 2017

    I am trying to create local notification when app runs in background. I have a timer function which can run background(I mean, just click home button when app runs)

    In this function, I call these codes,

     // Creates notification!
        func ShowNotification(title:String, body:String){
            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in})
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.badge = 1
            content.sound = UNNotificationSound.default()
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
            let request = UNNotificationRequest(identifier: "timer done", content: content, trigger: trigger)
            UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    This function can create notification when I call it after, press home button but, it can not create, I call it when app works in background.

    How can I solve this problem?
  2. Karamelli thread starter macrumors newbie

    Jul 29, 2017
    I realized that my app stops when app in background but, there wasn't this kind of problem in simulator.

    I could create a timer which can execute codes in background with simulator but, this app can not execute codes in real iPhone.

    I am confused o_O
  3. Mascots macrumors 68000


    Sep 5, 2009
    Few Notes:

    In your snippet: if requestAuthorization is being called from the background I don't think iOS will bubble up the dialog if your app isn't on screen so there's no way to accept it. Also, you are scheduling the notification before authorization has been granted, so that notification will be lost to the abyss. You should be requesting this access before scheduling anything.

    Next: Unless you ask for Background Execution Time, your app will be suspended (almost) the moment it enters the background; behavior on the simulator may be different.

    But even if you ask for background time to run your timer, there's no guarantee the system will give you enough time before it fires. Rather than attempting to keep your app alive to fire the notification from the background when the timer concludes, you should be setting that time on the notification to trigger and the system will handle that for you.

Share This Page