【发布时间】:2017-03-02 00:35:52
【问题描述】:
我有一个应用程序需要在后台运行才能执行其后台进程。我想在用户从多任务处理中关闭应用程序时向用户发送通知,以便我可以提示他们重新打开应用程序。我已经阅读了这里的讨论:Local notification on application termination,并尝试了这些解决方案,但没有一个能在用户终止应用程序时产生可靠的通知。
这是我的代码现在的样子,在我的 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事件。 没有 方法可以检测到这一点。确实,这正是stackoverflow.com/a/17988326/341994 所说的。
标签: ios objective-c iphone notifications