OGeek|极客世界-中国程序员成长平台

标题: ios - Iphone presentLocalNotificationNow 在后台应用程序时不会触发警报和声音 [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-13 13:27
标题: ios - Iphone presentLocalNotificationNow 在后台应用程序时不会触发警报和声音

我有一个应用程序注册位置更新、运行测试,有时当我在应用程序处于后台时进入某个区域时,我会收到带有声音的警报通知。有时我只在通知中心看到通知,并没有收到任何声音和警报... 怎样做才能始终收到声音和警报通知?

这就是我的看法

 UILocalNotification *localNotif = [[UILocalNotification alloc] init];
 localNotif.fireDate             = nil;
 localNotif.hasAction            = YES;
 localNotif.alertBody            = fbName;
 localNotif.alertAction          = @"View";
 localNotif.soundName            = UILocalNotificationDefaultSoundName;

[[UIApplication sharedApplication]presentLocalNotificationNow:localNotif];

这是应用委托(delegate)

- (void)applicationUIApplication *)application didReceiveLocalNotification (UILocalNotification *)notification
{
if (notification) 
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle"Alert"
                                                    message:notification.alertBody
                                                   delegate:self cancelButtonTitle"OK"
                                          otherButtonTitles:nil];


    [alertView show];

}

}

- (BOOL)applicationUIApplication *)application didFinishLaunchingWithOptionsNSDictionary *)launchOptions

{

facebook = [[Facebook alloc] initWithAppId:kAppId andDelegate:self];

UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if (notification) 
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle"Alert"
                                                        message:notification.alertBody
                                                       delegate:self cancelButtonTitle"OK"
                                              otherButtonTitles:nil];


    [alertView show];

}



return YES;
}



Best Answer-推荐答案


如果应用程序在后台运行,本地通知将不会收到警报或声音,因为它是由您的应用程序直接接收的。在这种情况下,您需要使用 presentLocalNotificationNow 呈现通知。

- (void)applicationUIApplication *)application didReceiveLocalNotificationUILocalNotification *)notification
{
    UIApplicationState applicationState = application.applicationState;
    if (applicationState == UIApplicationStateBackground) {
        [application presentLocalNotificationNow:notification];
    }
}

关于ios - Iphone presentLocalNotificationNow 在后台应用程序时不会触发警报和声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10369945/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://ogeek.cn/) Powered by Discuz! X3.4