简体   繁体   中英

How can I dismiss UILocalNotifications that appear when my app is in the background?

I'm working on an iPhone app that needs to remind a user to check in at regular intervals using UILocalNotifications. If they don't check in for a few hours, they may be reminded a couple times, but I just want to show the latest notification.

Now, if the app is open, I get a callback to didReceiveLocalNotification:(UILocalNotification *)notification, and I can keep track of whether there's a notification showing.

If the app is not running and the user clicks the -action- button, I get a callback to

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;

so I can dismiss any old notifications. However, if they click 'cancel', they have to click 'cancel' on a bunch of layered notifications, because as far as I can tell I don't get a callback (how could I, if the app isn't launched) and it doesn't seem like there's a flag or something when creating the UILocalNotification to have newer reminders from an app automatically dismiss other ones.

If the app is in the background but running, it's worse - first, I don't get any sort of callback there if the user click's cancel, so I have the same problem - the user has to click cancel a bunch of times. Second, if they click the action, I get a call to ApplicationDidBecomeActive, but there's no distinguishing between that and when the user just switches back and forth; I can dismiss and reschedule them here, but it doesn't seem to work perfectly, sometimes a few pop up before they're dismissed.

Any suggestions? If there were a way for the notifications to expire automatically that would be great too. I've looked online a bit and haven't found much help, but it seems like a big oversight, so hopefully there's some way to handle this gracefully.

Thanks.

You won't be able to get any callback when the user "cancel"s as you pointed out.

Is it possible to just remind the user once in your case? Only schedule one notification at a time and renew it on app launch/resume.

I have not tried the following yet, but I believe this can be a work around for your case. Use CLLocationManager 's startMonitoringSignificantLocationChanges

Every time the device's location changes significantly, your app will be launched in the background with options passed to locationManager:didUpdateLocations: and you can probably schedule a UILocalNotification from there!

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