Reputation: 628
I want to develop an alarm application in iOS. So far, I have created basic UI where the user can select the time when the alarm should trigger. The code schedules one local notification for this time using following code:
UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Helloooooo...";
content.body = @"Time to wake up!";
content.sound = [UNNotificationSound defaultSound];
//create trigger
UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:triggerDate repeats:NO];
NSString *identifier = @"test";
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier
content:content trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (error != nil) {
NSLog(@"Something went wrong: %@",error);
}
}];
Now, when this notification is triggered, I want to play music (like an alarm tone). After lot of research I understood that there are no callbacks for the notification triggered event when the application is in background.
Another approach I tried in which the code tries to call the playAlarmTone
method after certain timer:
UIApplication *app = [UIApplication sharedApplication];
//create new uiBackgroundTask
__block UIBackgroundTaskIdentifier bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//and create new timer with async call:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//run function methodRunAfterBackground
NSTimer* t = [NSTimer scheduledTimerWithTimeInterval:lroundf(secondsBetween)
target:self
selector:@selector(playAlarmTone)
userInfo:nil
repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:t forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
});
But with this approach, the music is not playing if the alarm clock is set to more than 15 minutes from the current time.
What is a methods to run specific task after time interval of "x" minutes?
I found an alarm application on the App Store which can play alarm music for infinite time when alarm is triggered. How this app can determine when to start the alarm music?
Upvotes: 0
Views: 713
Reputation: 1
Did you already consider using NSTimer scheduledtimerwithtimeinterval? This could be used to perform an action after a time interval as per your need. Also, check this article http://andrewmarinov.com/building-an-alarm-app-on-ios/ from Andrew.
Upvotes: 0
Reputation: 11039
You should specify the music name by setting the sound
property to your content
.
So instead of:
content.sound = [UNNotificationSound defaultSound];
You should set:
content.sound = [UNNotificationSound soundNamed:@"yourSoundName.mp3"];
Also, make sure that your music length is not longer than 30 seconds.
Upvotes: 0