用户终止应用程序(iOS)时的通知
问题描述:
我有一个应用程序需要在后台运行,以便执行其后台进程。我想在用户关闭多任务应用程序时向用户发送通知,以便我可以提示他们重新打开应用程序。我已阅读这里的讨论:Local notification on application termination,并尝试过这些解决方案,但没有一个在用户终止应用程序时产生可靠的通知。用户终止应用程序(iOS)时的通知
这里是我的代码看起来像现在,在我的AppDelegate.m文件:
- (void)applicationWillTerminate:(UIApplication *)application
{
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
[center removeAllDeliveredNotifications];
//Try and alert the user
UILocalNotification *notification = [[UILocalNotification alloc] init];
notification.alertBody = @"App was terminated unexpectedly. Notification-based logging won't work. Tap to restart App!";
notification.soundName = UILocalNotificationDefaultSoundName;
[application scheduleLocalNotification:notification];
// Saves changes in the application's managed object context before the application terminates.
[self saveContext];
}
在模拟器的调试模式,这种解决方案总是提供当应用从多任务处理关闭的通知。不幸的是,在我的手机上,我偶尔会在应用程序终止时收到此通知。很多时候,我从多任务处理中杀死了该应用程序,并且没有通知出现。
我在重复提问,因为对链接帖子的回复已经过去了几年,我有理由相信这是可以实现的。 Moment和TripLog应用程序都具有我想要的确切行为。
如果任何人有一个可靠的解决方案,当他们从多任务关闭应用程序时向用户发送本地通知,那将非常感激。我在Objective C中编写代码,因此Objective C中的解决方案将是理想的。
答
没有办法确保您的应用在后台继续运行。运行时可以随时在后台以静默方式终止它,并且在发生这种情况时无法获得事件。
似乎成功完成此操作的应用程序实际上可能是正在做某事在后台,也就是说,例如,他们正在进行核心位置更新或播放声音。这种专业行为大大增加了在后台获得applicationWillTerminate
的机会。
“很多时候我从多任务中杀死了应用程序,并且没有通知出现”也许你没有收到通知,因为该应用程序已被系统在后台终止,因此不再运行,并且没有applicationWillTerminate事件。没有办法检测到这一点。的确,这正是http://stackoverflow.com/a/17988326/341994所说的。 – matt