2

我想在我的应用程序终止时向用户显示(本地)通知,无论是由 iOS 本身还是由用户通过任务切换器。

当 iOS 由于内存压力而终止应用程序时,applicationWillTerminate会在 my 上调用该函数AppDelegate,因此我可以在这种情况下安排本地通知。

但是,当用户通过在任务切换器中将应用程序滑动到顶部来终止应用程序时,applicationWillTerminate不会调用该函数(如 Apple 文档和 SO 上的各种答案中所述)。然而,在这种情况下,有些应用程序仍然成功地向用户显示(本地)通知(尤其是健身跟踪应用程序,例如 Human),要求用户重新启动应用程序以便后台跟踪可以继续。

我可以想到一些(主要是笨拙的,或者至少是耗电的)方法来完成这项工作,但是有没有一种很好的方法可以向用户显示这样的通知?特别是在应用程序被用户杀死后几乎立即执行此操作,这排除了许多可能的解决方法,即在后台每隔 n 秒安排和取消本地通知......

4

2 回答 2

1

找到它......显然,显示通知的应用程序就像我想要显示的那样通过使用后台位置更新来(重新)安排本地通知,因此它永远不会出现,一旦它们被用户杀死通知保持活跃并触发。

听起来不太好,但除了定期从服务器 ping 应用程序之外,这可能是唯一的方法。

最好有一种更体面(和节能)的方式来做到这一点,例如,在应用程序终止之前始终有时间做某事,无论终止的原因是什么。

于 2015-08-12T07:15:30.953 回答
0

我试过这样:

  • 必须启用后台模式(蓝牙、voip、定位服务)
  • 将此代码添加到didFinishLaunchingWithOptions

    [self addLocalNotification];
    [NSTimer scheduledTimerWithTimeInterval:9.0f
                                         target:self
                                   selector:@selector(addLocalNotification)
                                       userInfo:nil
                                        repeats:YES];
    
  • addLocalNotification

    - (void) addLocalNotification{
    NSDate * theDate = [[NSDate date] dateByAddingTimeInterval:10]; // set a localnotificaiton for 10 seconds
    
    UIApplication* app = [UIApplication sharedApplication];
    NSArray*    oldNotifications = [app scheduledLocalNotifications];
    
    
    // Clear out the old notification before scheduling a new one.
    if ([oldNotifications count] > 0)
        [app cancelAllLocalNotifications];
    
    // Create a new notification.
    UILocalNotification* alarm = [[UILocalNotification alloc] init];
    if (alarm)
    {
        alarm.fireDate = theDate;
        alarm.timeZone = [NSTimeZone defaultTimeZone];
        alarm.repeatInterval = 0;
        alarm.alertBody =@"App must run" ;
    
        [app scheduleLocalNotification:alarm];
    }}
    

它对我有用。addLocalNotification只要应用程序运行/后台运行,就会运行。一旦终止,已安排的本地通知将按时触发。我们可以根据自己的兴趣改变时间间隔。

于 2015-10-27T06:46:42.183 回答