【问题标题】:Alarm not working when device is locked设备锁定时警报不起作用
【发布时间】:2014-02-03 15:49:27
【问题描述】:

当核心位置框架委托方法触发时,我想在我的 IOS 设备中触发警报。当应用程序处于前台时,警报会正确响起。但是当设备被锁定时,警报功能不起作用。这是我使用的代码。

UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [NSDate date];

localNotification.alertBody = @"body";
localNotification.soundName = @"RING.WAV";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

是因为我使用了 UILocalNotification 类吗?如果有,是否有替代方案。

锁屏时显示本地通知提示体,但不响闹。

编辑:

在 appdelegate 中,我让代理接收本地通知

- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notification{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/RING.WAV", [[NSBundle mainBundle] resourcePath]]];

NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = -1;

if (audioPlayer == nil)
    NSLog(@"error :%@",[error description]);
else 
    [audioPlayer play];
}

我发现当设备被锁定时这个方法不会被触发。当设备被锁定时,有没有办法根据 UILocalNotification 触发警报?

【问题讨论】:

  • 您的应用是 VoIP 还是音频?因为当设备被锁定时,应用程序会停止,所以它永远不会执行任何代码。您可以在睡觉前执行代码并安排将来的通知。
  • 但是当应用程序在前台时这工作正常。只有当它锁定时,才会出现此问题。
  • 您的代码何时何地被调用?
  • 以上代码是从 CLLocationManager 委托方法中调用的。
  • 您是否在 app-info.plist 中指定了后台模式?你能在你的代码前放一条 NSLog 消息,看看代码是否真的执行了吗?

标签: ios iphone ipad uilocalnotification


【解决方案1】:

你需要告诉手机你的通知有动作

[localNotification setAlertAction:@"My Action"];
[localNotification setHasAction:YES];

【讨论】:

  • 我没有发布那部分代码,但实际上我确实设置了一个操作。而且它不起作用。
  • 您的通知触发日期设置为使用上面编写的代码立即生效。你的应用程序也是这样吗?你可以为你的fireDate试试这个[[NSDate alloc] initWithTimeInterval://your time ahead of current date you want the notification to go off (try 10 for ten seconds) sinceDate:[NSDate date]];
  • app在前台运行时不应该也存在同样的问题吗?在前台,应用运行良好。
  • @alinoz 关于您的应用信息列表是正确的。你看过这个答案吗? link
  • hasAction的默认值为true,如果没有修改就不需要设置了。
【解决方案2】:

在这种情况下,设置音频会话属性可以解决问题。

 [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord withOptions:AVAudioSessionCategoryOptionDefaultToSpeaker error: nil];
UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute,sizeof (audioRouteOverride),&audioRouteOverride);
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
[AVAudioSession sharedInstance] setActive: YES error: nil];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-18
    • 2015-10-19
    相关资源
    最近更新 更多