17

我遇到了一些非常恼人的问题UILocalNotification

在完成一个我几乎完成的应用程序时,我注意到无论我尝试什么,我都无法让本地通知工作。

因此,我没有浪费时间,而是决定回归基础,看看我是否能让它们发挥作用。

我创建了一个新的基于 XCode 视图的应用程序,并替换-viewDidLoad为:

- (void)viewDidLoad
{
    UILocalNotification * theNotification = [[UILocalNotification alloc] init];
    theNotification.alertBody = @"Alert text";
    theNotification.alertAction = @"Ok";
    theNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:10];

    [[UIApplication sharedApplication] scheduleLocalNotification:theNotification];
}

但是,这也没有任何作用。
我希望在启动应用程序 10 秒后看到通知,但什么也没有出现。
另外,我在我的 iPhone 和模拟器上都进行了测试。

我在这里错过了一些非常重要的东西吗?(我已经搜索了 Apple 文档,但找不到任何关于为什么会发生这种情况的信息

谢谢

4

3 回答 3

43

UILocalNotifications 仅在应用程序运行(或在后台运行)时自动显示。如果应用程序正在运行并且触发了本地通知,则调用UIApplicationDelegate'- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification方法并且系统不显示任何内容(也不播放声音)。如果要显示通知,请UIAlertView在委托方法中创建自己。

于 2011-02-11T22:04:45.680 回答
16

只是我个人愚蠢冒险的评论......

我有同样的问题,但我的问题是我忘记为 alertBody 赋值。如果不设置 alertBody,则不会显示通知。

于 2011-07-14T21:29:18.847 回答
12
  1. fireDate 必须是未来时间。
  2. 应用程序必须在后台运行,或者已关闭。
  3. 还有一件事,不要忘记显示查询是否允许推送,将以下代码添加到 AppDelegate:

    -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 
      if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
           UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil]; 
           [application registerUserNotificationSettings:settings]; 
      }
    }
    
于 2015-10-22T09:25:53.733 回答