Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

Karamelli

macrumors newbie
Original poster
Jul 29, 2017
7
0
Hi,

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,

Code:
 // 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?
 
Last edited by a moderator:
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
 
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.