ios nstimer在后台运行检查报警时间等于当前时间并播放audio

我GOOGLE了几个小时,但无法find任何信息,如果有任何方式来保持运行NSTimer活动时,应用程序在后台运行? 请帮助我,当应用程序是背景,然后一个function运行,每秒检查报警时间等于当前时间,然后播放audio,并打开closures报警页面如果有人知道闹钟应用程序开源,并在后台运行,请与我分享在这里,我尝试这个,但是这不起作用

- (void)applicationDidEnterBackground:(UIApplication *)application { inBackground=YES; UIApplication* app = [UIApplication sharedApplication]; bgTask = [app beginBackgroundTaskWithExpirationHandler:^{ [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }]; // Start the long-running task and return immediately. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ while (inBackground == YES) { [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(checkAlert) userInfo:nil repeats:YES]; } [app endBackgroundTask:bgTask]; bgTask = UIBackgroundTaskInvalid; }); } -(void)checkAlert { NSLog(@"Chalaaaaaa"); NSString *checkAlarmOnOff = [defaults stringForKey:@"setAlarm"]; // Switch Alarm From Setting page NSString *SwitchAlarm=[defaults stringForKey:@"setSwitchAlarm"]; if([SwitchAlarm isEqualToString:@"ON"]) { if([checkAlarmOnOff isEqualToString:@"YES"]) { if(![alarmRun isEqualToString:@"Yes"]) { NSString *getAlarmTime = [defaults stringForKey:@"setAlarmTime"]; NSLog(@"AA-%@",getAlarmTime); NSLog(@"BB-%@",globalClockTime); if([getAlarmTime isEqualToString:globalClockTime]) { [self MusicAction]; [_audioPlayer play]; UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Alarm" message:@"Alarm On" delegate:self cancelButtonTitle:@"Off" otherButtonTitles:nil, nil]; [alert show]; alarmRun=@"Yes"; } } } } } 

请帮帮我,

NSTimer不会在后台运行。 并使用beginBackgroundTaskWithExpirationHandler不会保存您的问题。 与后台任务你的应用程序可以运行最多10分钟,然后将被杀死

你应该使用UILocalNotification

 UILocalNotification *localNotification = [[UILocalNotification alloc] init]; localNotification.fireDate = dateTime; localNotification.alertBody = [NSString stringWithFormat:@"Alert Fired at %@", dateTime]; localNotification.soundName = UILocalNotificationDefaultSoundName; [[UIApplication sharedApplication] scheduleLocalNotification:localNotification]; 

用NSCalendar计算时间并添加以下行:

 localNotification.repeatInterval = NSDayCalendarUnit; 

调度本地通知将做你想要的。使用日历和date组件发射当地通知今天在特定的时间或在特定的时间在某些其他date在这里你去

 NSCalendar *calendar = [NSCalendar currentCalendar]; // Split the date into components but only take the year, month and day and leave the rest behind NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]]; // Current Date // Build the date formatter NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setDateFormat:@"h:mm a"]; // Convert the string time into an NSDate NSDate *time = [formatter dateFromString:@"1:59 PM"]; //your hour:minutes am/pm values // Split this one in components as well but take the time part this time NSDateComponents *timeComponents = [[NSCalendar currentCalendar] components:(NSHourCalendarUnit | NSMinuteCalendarUnit ) fromDate:time]; // Do some merging between the two date components dateComponents.hour = timeComponents.hour; dateComponents.minute = timeComponents.minute; // Extract the NSDate object again NSDate *fireTime = [calendar dateFromComponents:dateComponents]; NSLog(@"Fire Time is FireTime %@", fireTime); localNotification.fireDate = fireTime; 

如果你在模拟器中检查它,那么它将打印TimeZone的空闲date/时间值。 不要担心,通知将被设备的本地时区解雇。

请注意,苹果肯定会拒绝任何滥用其后台政策的应用程序,因此只能用于个人和企业用途!

那么我们将如何滥用iOS背景政策呢? 我们将宣布我们的应用程序为背景音乐播放器,但不能播放任何音乐。

1)首先确保您的应用程序在function – >背景模式打开,“audio和AirPlay”启用。 还要确保你是importAVFoundation

2)现在创build你的无声音乐文件。 我用沉默的一秒钟MP3文件取得了成功。 audio文件不必沉默,但为什么用随机audio文件吓唬用户? 将其添加到“支持文件”类别。

3)添加一个属性到视图控制器,将举行沉默的audio播放器。

 Swift: var player = AVPlayer() Obj-c: @property (nonatomic, strong) AVPlayer *player; 

4)现在,您应该设置audio会话。 我select在viewDidLoad中的视图控制器的单个视图在演示应用程序。

 Swift: do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback, withOptions: .MixWithOthers) try AVAudioSession.sharedInstance().setActive(true) } catch { print(error) } Obj-c: NSError *sessionError = nil; [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:&sessionError]; 

类别AVAudioSessionCategoryPlayback是less数允许背景的类别之一。 选项AVAudioSessionCategoryOptionMixWithOthers将确保您的无声audio不会停止任何当前正在播放的背景audio,并且确保当用户将来播放音乐时,它不会启动您的后台任务。 一个好的开发者也会检查返回值和sessionError,但是我不是一个好的开发者。

5)现在为您的无声audio文件创build实际的播放器项目。 如果您以不同的方式embeddedaudio文件,请随时调整以适应此操作。 这里没有欺骗。

 Swift: let path = NSBundle.mainBundle().pathForResource("30sec", ofType: "mp3") let item = AVPlayerItem(URL: NSURL(fileURLWithPath: path!)) player = AVPlayer(playerItem: item) Obj-c: AVPlayerItem *item = [AVPlayerItem playerItemWithURL:[[NSBundle mainBundle] URLForResource:@”silence” withExtension:@”mp3″]]; [self setPlayer:[[AVPlayer alloc] initWithPlayerItem:item]]; 

6) 这是诡计! 这可以确保audio播放器在播放完声音文件后保持活动状态。 另一种方法是保持循环静音轨道,但为什么浪费更多的CPU周期(和电池)?

 Swift: player.actionAtItemEnd = .None Obj-c: [[self player] setActionAtItemEnd:AVPlayerActionAtItemEndNone]; 

7)现在,只要你想保持在后台的应用程序,只要打电话

 Swift: player.play() Obj-c: [[self player] play]; 

而且即使在用户切换应用之后,你的应用也会继续工作。