iphone - 当应用程序处于后台或事件状态时的 UILocalNotification

标签 iphone ios timer uilocalnotification

在我的应用程序中,我必须以自定义时间间隔发出通知(文本和声音)。即 1 分钟、2 分钟、3 分钟到 59 分钟,我的应用程序处于后台或应用程序处于事件状态。我为此使用本地通知。

这里有两个问题:

  1. 当我从日期时间选择器中选择任何时间时,我仅在 1 分钟内就收到了通知。对于例如。当我选择 5 分钟并启动计时器时,通知每 1 分钟触发一次,而不是 5 分钟内触发一次。我如何在自定义时间间隔内收到通知以及如何重复它直到我停止计时器开关。

  2. 我在后台收到文本和声音,但当我的应用程序处于事件状态时,我只收到文本而不是声音。那么当我的应用程序处于事件状态时如何播放声音。

请给我一些建议。提前致谢。

最佳答案

  1. 无法自定义时间间隔
    您无法为 UILocalNotification 设置自定义时间间隔,只能使用 NSCalendarUnits 作为重复间隔,例如 NSMinuteCalendarUnit

      notification.repeatInterval = NSMinuteCalendarUnit
    
  2. 如果您的应用程序位于前台(事件),则需要提供自定义警报 View 和声音。系统只会调用applicationDidReceiveNotification。为此,您可以使用 UIAlertViewAVAudioPlayer

    -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
    {
    
      UIApplicationState state = [[UIApplication sharedApplication] applicationState];
     // checking the state of the application
      if (state == UIApplicationStateActive) 
       {
          // Application is running in the foreground
          // Showing alert
          UIAlertView *alert = [[UIAlertView alloc]initWithTitle:alertTitle message:alertMessage delegate:self cancelButtonTitle:cancelButtonTitle otherButtonTitles:otherButtonTitle, nil];
          [alert show];
          [alert release];
    
        //Playing sound
        NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:@"%@/%@", [[NSBundle mainBundle] resourcePath],notification.soundName]];
    
        AVAudioPlayer *newAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
        self.audioPlayer = newAudioPlayer;
        self.audioPlayer.numberOfLoops = -1;
        [self.audioPlayer play];
        [newAudioPlayer release];
      }
    }  
    
     - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
      {
        [self.audioPlayer stop];
      }
    

关于iphone - 当应用程序处于后台或事件状态时的 UILocalNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16333676/

相关文章:

iphone - 从不兼容类型 'AppDelegate *' 分配给 'id<UIApplicationDelegate>'

ios - 如何在多个场景中通过步进器更改字体大小?

ios - 使用 JSON 进行基本身份验证

Java:计时器(等待 x 秒)

java - 带计时器的 ServletContextListener 未在控制台中显示输出

c++ - 使用 QueryPerformanceCounter() 倒计时

javascript - Mobile Safari (iPhone) 对 Javascript GET 请求有 30 秒以上的延迟

iphone - 如何实现相册应用?

ios - 在 iOS 7.1 中,UISearchBar 的文本和占位符属性不再起作用

ios - NSData 到数据 swift 3