应用程序在后台时未触发 iOS 本地通知

Posted

技术标签:

【中文标题】应用程序在后台时未触发 iOS 本地通知【英文标题】:iOS Local Notofications not firing while app is in background 【发布时间】:2011-08-12 02:32:51 【问题描述】:

当我的 ios 应用退出时,它会注册一系列本地通知,这些通知会在特定时间更新徽章编号。本地通知不会弹出弹出窗口,它们只是更新徽章。在我不支持多任务处理的旧 iPod touch 上,这非常有效。然而,在我的多任务设备上,我遇到了一个非常奇怪的错误:当我“退出”应用程序时(即它仍在后台运行,但我正在做其他事情),本地通知没有触发。当应用程序在后台时,本地通知不会触发有什么原因吗?

创建本地通知的代码循环运行(我创建了一堆):

    UILocalNotification *localNotification = [[UILocalNotification alloc] init];
    localNotification.applicationIconBadgeNumber = totalCount; // a number generated earlier in the code
    localNotification.timeZone = [NSTimeZone defaultTimeZone];
    localNotification.fireDate = endDate; // a date generated earlier
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [localNotification release];

我还在我的应用委托中创建了以下函数,它告诉我在应用进入后台之前设置了多少通知:

- (void)applicationDidEnterBackground:(UIApplication *)application 
    NSLog(@"# Notifications: %d", [[[UIApplication sharedApplication] scheduledLocalNotifications] count]);

应用程序进入后台时不断告诉我有 64 条通知(应该设置的数量)。

【问题讨论】:

你能告诉我们触发本地通知的代码吗? 感谢您的建议。我添加了一些代码。 你解决过这个问题吗? 【参考方案1】:

从 Apple 的开发者文档中查看以下内容: “设备上的每个应用程序限制为 64 个预定的本地通知。系统会丢弃超过此限制的预定通知,只保留最快触发的 64 个通知。重复通知被视为单个通知。”

您的问题可能与安排的通知数量有关吗?

您可以在http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/WhatAreRemoteNotif.html找到更多信息

【讨论】:

【参考方案2】:

@Jason,您至少需要设置 local notificationalertBody 以显示警报视图,仅此而已。

另外,如果您不想在警告框中显示查看选项,请将hasAction 属性设置为 NO。

【讨论】:

抱歉,这并不能完全回答我的问题...我对显示警报视图不感兴趣。我只想更新徽章编号。 您还需要检查触发日期,如果日期早于当前日期,则不会触发通知,只会调用应用程序在您的应用程序委托中接收到本地通知方法。【参考方案3】:

Swift 版本:

func applicationDidEnterBackground(application: UIApplication) 
       let notification = UILocalNotification()
        notification.alertBody = "App has been entered in background" 
        notification.alertAction = "open" 
        notification.fireDate = NSDate() 
        notification.soundName = UILocalNotificationDefaultSoundName 
        UIApplication.sharedApplication().scheduleLocalNotification(notification)
    

【讨论】:

以上是关于应用程序在后台时未触发 iOS 本地通知的主要内容,如果未能解决你的问题,请参考以下文章

当 iOS 10 应用程序在后台时,有啥方法可以触发本地通知?

当应用程序在后台 iOS 11 中时,UNNotification 本地通知用户点击不会触发委托

应用程序在 iOS 11 中处于后台时未收到推送通知

iOS 本地通知 - 在后台时回调

是否可以在事件 IOS 之后触发本地通知?

如果在 ios 中收到通知时从后台删除应用程序,didReceiveLocalNotification 不会触发