应用程序为后台或活动时的UILocalNotification

时间:2013-05-02 08:38:54

标签: iphone ios timer uilocalnotification

在我的应用程序中,我必须以自定义时间间隔发出通知(文本和声音).i.e 1分钟,2分钟,3分钟到59分钟我的应用程序处于后台或应用程序处于活动状态。我正在使用本地通知。

我有两个问题:

  1. 当我从我的约会时间选择器中选择任何时间时,我只在1分钟内收到通知。对于Eg。当我选择5分钟并启动计时器时,通知每隔1分钟发射一次而不是5分钟。如何在自定义时间间隔内收到通知,如何重复此操作直到我停止定时器切换。

  2. 我在背景中都有文字和声音但是当我的应用程序处于活动状态时,我只得到文字不合理。那么当我的应用程序处于活动状态时,如何播放声音。

  3. 请建议我一些想法。在此先感谢。

1 个答案:

答案 0 :(得分:1)

  1. 无法自定义时间间隔
    您无法为UILocalNotification设置自定义时间间隔,您只能将 NSCalendarUnits 用于repeatInterval,例如NSMinuteCalendarUnit

      notification.repeatInterval = NSMinuteCalendarUnit
    
  2. 如果您的应用处于前台(有效),则需要提供自定义alertView和声音。系统仅会调用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];
      }