简体   繁体   中英

Execute code when app in background and a Local Notification fires

Here a very tricky situation: I'm writing an alarm app in swift. At the moment the alarm is fired the application will most likely be in background or killed or even worse the iPhone is locked. As soon as the alarm is fired the app should set another notification automatically while in background. I'm able to do this in AppDelegate only if the app is in foreground, but in background, I'm only able to set a notification with a nice attachment and sound, but no code is executed. I'm not able to call a method after a local notification was received in background with a locked device. Help would be very appreciated. I'm not sure there is a solution. Thank you very much.

Reading didReceiveRemoteNotification it says that this method is called if your app is running in the foreground or background.

What you may find useful is

In addition, if you enabled the remote notifications background mode, the system launches your app (or wakes it from the suspended state) and puts it in the background state when a remote notification arrives. However, the system does not automatically launch your app if the user has force-quit it. In that situation, the user must relaunch your app or restart the device before the system attempts to launch your app automatically again.

So, I don't the think you can work around the killed scenario. But with background mode enabled you can at least wake the app from at most the suspended mode.

Read Apple's Background Execution article, especially the section Understanding When Your App Gets Launched into the Background . Where it says a background execution is when

A push notification arrives for an app and the payload of the notification contains the content-available key with a value of 1.

You may be able to do some or most of what you want in here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM