Alarm clock with answer-to-disable on iOS - iphone

Apple resources contain a lot of informations but there's one thing which I can't clearly understand reading about audio and notification.
Is it possible to make an app, running in background which produce sound (even if phone is locked and/or silenced) and when it's happend user must solve eg. equation to turn it off?
p.s. For now I mostly use Cordova framework but Obj-C tip will also be nice.

Yes it is posssible.
You can use UILocalNotification for this.
Also apple allows apps that are playing music in background.
Please check these links for the background task feature:
ManagingYourApplicationsFlow
ios multitasking background tasks
How to handle background audio playing while ios device is locked or on another

You can change Local Notifications for NSTimers (keeping them alive in inactive mode with https://github.com/mruegenberg/MMPDeepSleepPreventer) and calculate the time interval for each alarm. That way you can then play an audio even with the screen locked and the sound off pasting this in your - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions:
// Let the sound run with the screen blocked
NSError *setCategoryErr = nil;
NSError *activationErr = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error:&setCategoryErr];
[[AVAudioSession sharedInstance] setActive:YES error:&activationErr];
But you will have some problems:
The app must be playing an audio file each 10 seconds so it doesn´t deep sleep and kills all NSTimers.
Apple could reject your app for doing so.
You can´t close the app with the home button, otherwise, it won´t work.
You must open the app every time you need to use the alarm (you can´t schedule and forget).
When the alarm fires, you only have the lock screen of the iPhone and need to unlock it first and then stop the alarm from inside the app.
In Apple they don´t want competitors for their alarm clock app, that's for sure! Almost all the alarm clock apps you see in the App Store use this poor approach.

Related

How to keep my app longer than 10 min. in the background?

I know that in iOS, background apps can only be running
Finite-length tasks (10 min)
Location updates
VoIP
Audio
Is there a way for my application to avoid being terminated after being 10 min. in the background? I will not be submitting my app to the app store, so everything is allowed (private frameworks, using the gps even if I don't need it) I know apple does not recommend this, but it is just for monitoring purposes. I need it to be running without a limit.
I explored several possibilities including the VoIP , but it only gives me 30 seconds every 10 minutes, which is not enough. I also read this post:
iPhone - Backgrounding to poll for events
in which JackPearse specified a way to "revive" the 10 minute finite-length task using the VoIP 30 second task. But I don't want my task to start and end every 10 minutes, it must run continuosly.
I also tried his UPDATE2, but it's not working for me.
I even tried intercepting the UIEvent with GSEvent.type 2012, which seemed to be the one ending my background task, but no luck. Strangely, my background task is never ended when I have Xcode opened and debugging, but when I don't (test the simulator alone) it ends after 10 minutes.
I have already tried some way(nsrunloop,*performselectoronmainthread*) like that.It's works well in simulator (not in device because apple crashes automatically after sometimes) when the app goes to background.
status is a BOOL variable.
- (void)applicationDidEnterBackground:(UIApplication *)application {
while (!**status**) {
[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:60.0]];
[self goBackground];
}
}
I found out how to keep my Application in the background for longer than 10 minutes by continuously playing a song in the background.
On the AppDidFinishLauching:
[[AVAudioSession sharedInstance] setActive:YES error:&error];
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];
NSURL *url = [NSURL fileURLWithPath:...]; //Song URL
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
player.numberOfLoops = -1;
[player play];
In the AppDidEnterBackground you can perform a selector in background, which can last forever. The App will not be interrupted, you can check UIApplication backgroundtimeRemaining and see it never decreases.
Of course, declare the app as a background audio App in the plist.

AudioSession - want to stop everything being played in background?

I got a need to stop (or mute at least) music/sound that is played in iPhone.
Important: I want my app will do that it even if is in background-state!
I'm using:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategorySoloAmbient error:nil]];
[[AVAudioSession sharedInstance] setActive: YES];
The issue is that everything is being stopped, even streaming music from some other app, but only if app is in FOREGROUND. As wrote before, I want it to be working also in BACKGROUND.
I did simple research and realized it's somehow possible, these apps prove:
App Store - Streaming Music Timer or
App Store - Music Sleep Timer
I guess my solution with SoloAmbient can be not so perfect and it may be a wrong way.
Does anybody know how could I stop/sleep/pause/mute global music even if app will be in background state?
These apps I pointed out are doing basically this thing...
You need to enable the audio background mode.
Add the Required Background Modes key to your app's Info.plist and add the App Plays Audio key to it.
See this tutorial for more.
EDIT Also, you probably want the AVAudioSessionCategoryPlayback category, not AVAudioSessionCategorySoloAmbient

Set device volume - UILocalNotification - iphone in silent mode

How can i set volume of device(in silent mode) when UILocalNotification is generated when application is in background? I am working on alarm app, so sound has to be played in silent mode too and i am handling app alarm using local notification.
Badly stuck in this issue, not able to play alarm in silent mode.
Please help..
It is simply not possible. The UILocalNotification popup and sound are generated by another system process, and that process observes the device silent mode, so it won't play the notification sound if the device is on silent.
if you want your alarm clock app to play the alarm sound even when device is in silent mode, you will have to play the alarm sound right from your app. To do that, you will need to keep your app running in the background, then you will have to play the alarm sound file while in the background. The later can be done by specifying "audio" that the "Required background modes" property in your info.plist (you will have to add that property to your plist file)
Now, using AVAudioPlayer, there is a way to play sound even when device is silent by setting the Audio session category like this:
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
Hope this helps.
You have to realize that local notifications are triggered even your app is killed. That leads me to conclusion that it is probably not possible to do that.
But you can try that like this:
UInt32 sessionCategory = kAudioSessionCategory_AmbientSound;
AudioSessionSetProperty(kAudioSessionProperty_AudioCategory, sizeof(sessionCategory), &sessionCategory);
right before you make your audio session active.

iOS 4 Alarm Clock App with Multitasking Support

I'm making an alarm clock app with multitasking support. However, I'm stuck with some limitations of the sdk.
I need to play selected alarm sound whenever the alarm time comes with some properties set by the user.
These properties:
- Alarm sound can be a music from the user's iPod library, and also some sound files in application bundle.
- Alarm sound can be set to play as progressive.
Moreover, alarm sound must be played in background in a loop until the user cancels or wakes the app.
First logical thing that came to my mind was to use local notifications, but with local notifications you can play sound files that are only in app bundle(not iPod music) and that are at most 30 seconds long. Also you are not get notified when the user cancels the notification alert, iOS just stops playing your sound.
Now I'm thinking of using background audio playing option and play silence until the alarm time, and then play the alarm sound while also showing a local notification without sound. But again how will I know if user cancelled the local notification alert and stop playing audio. However according to Apple's documentation iPod music playing(and use of shared resources) is still not allowed for an app that is playing background audio.
I also can't understand how some other apps are doing some of these features. For example, Night Stand HD can play iPod music while in the background, and an app named "Progressive Alarm Clock" can play progressive sound while in the background.
Any ideas and suggestions on these issues? Any of your help will be greatly appreciated
I would say what you want to do is not possible with the current restrictions of iOS. That said you can probably fake a progressive alarm by doing what the developer of Progressive Alarm Clock do to play the progressive alarm. By scheduling many local notifications, one after each other. He has divided the alarm sounds into chunks of say 10 s each with progressive volume levels. This is a very crude example to show how the progressive alarm can be faked.
UILocalNotification *notif1 = [[UILocalNotification alloc] init];
notif1.fireDate = [NSDate dateWithTimeIntervalSinceNow:15];
notif1.soundName = UILocalNotificationDefaultSoundName;
notif1.alertBody = #"Alarm";
[[UIApplication sharedApplication] scheduleLocalNotification:notif1];
[notif1 release];
UILocalNotification *notif2 = [[UILocalNotification alloc] init];
notif2.fireDate = [NSDate dateWithTimeIntervalSinceNow:20];
notif2.soundName = UILocalNotificationDefaultSoundName;
[[UIApplication sharedApplication] scheduleLocalNotification:notif2];
[notif2 release];
This will first display a notification and play the default sound after 15 seconds. After 5 seconds more the sound will be played again. By having a bunch of sound files where the volume is increasing the progressive sound can be faked just by scheduling more local notifications. This will of course only work if you have an alarm sound that can be easily divided into chunks, just like the bells in Progressive Alarm Clock. Unfortunately you can't cancel the alarm by tapping cancel in the notification. You have to start the application to do that.
Whatever the Progressive Alarm Clock developer is doing, it's not what Robert Höglund is describing, AFAIK, since the alarm will sound even if the phone is in silent, and UILocalNotification doesn't seem to have any way to allow for this. In addition, if you kill the app manually while an alarm is pending, the app will notify you that it needs to relaunch. This seems to suggest that it must be somehow running in the background.

What happens to an iPhone app when iPhone goes into stand-by mode?

My app uses NSTimer and it appears that NSTimer doesn't fire when the iPhone goes into the stand-by mode (either by pressing the hardware button or by the idle timer).
When I activate the iPhone again, my app is still in the foreground. What happens to third party apps when the iPhone is the stand-by mode?
Although it's not evident here, I believe the original poster did find an answer to his question by starting a thread (available here) in the iPhone Developer Forums (which I eventually had to find myself because the information wasn't shared here).
In case someone else has the same question and finds the page in the future, here's a helpful response that was posted by someone on the Apple forum called "eskimo1" (which I have edited slightly such that it is easier to read without having the context provided by the entire original thread):
Regarding iPhone app status terminology, "active" does not mean "awake", it means "attached to the GUI". Think of it being analogous to "frontmost" in Mac OS X. When you lock the device your app deactivates but the device may or may not go to sleep
iPhone OS rarely sleeps if the device is connected to main power (i.e., via USB). It can sleep if running on battery, however.
A short time after the screen is locked (20 seconds according to Oliver Drobnik), the device sleeps. This is like closing the lid on your laptop; all activity on the main CPU halts.
This does not happen if the device is playing audio in the right audio session. See DTS Q&A QA1626 "Audio Session - Ensuring audio playback continues when screen is locked" for details.
Note that the idleTimerDisabled property (which can be turned on to prevent the screen from turning off while the app is running) is about locking the screen after user inactivity. It's not directly related to system sleep (it's indirectly related in that the system may sleep shortly after it's locked).
See Application Interruptions in the iPhone OS Programming Guide, especially the applicationWillResignActive and applicationDidBecomeActive events. (The whole guide is certainly worth reading.) When You ignore the events, the timer seems to go on for a while and then stops. Sounds logical, the application could easily drain the battery if kept running. And what exactly happens to the application? I guess it simply does not get any CPU time – it freezes and only thaws when You turn the machine back “on.”
My first advice is do not disable the idle timer, that is just a hack. If you want to keep a timer alive during UI events run the timer on the current run loop using NSCommonModes:
// create timer and add it to the current run loop using common modes
self.timer = [NSTimer timerWithTimeInterval:.1 target:self selector:#selector(handleTimer) userInfo:nil repeats:YES];
[[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
I used the information on this post for a small sample that I was building. This is the code that I used when I initiated the playback to prevent the audio from stopping:
AudioSession.Category = AudioSessionCategory.MediaPlayback;
And when the application is done with the playback to reset to the original value:
AudioSession.Category = AudioSessionCategory.SoloAmbientSound;
The full sample is here:
http://github.com/migueldeicaza/monotouch-samples/tree/master/StreamingAudio/
I was faced with this issue recently in an app I am working on that uses several timers and plays some audio prompts and made two relatively simple changes:
In the AppDelegate I implemented the following methods and there mere presence allows the app to continue when the screen is locked
// this receives the notification when the device is locked
- (void)applicationWillResignActive:(UIApplication *)application
{
}
// this receives the notification that the application is about to become active again
- (void)applicationWillBecomeActive:(NSNotification *)aNotification
{
}
references: UIApplicationDelegate Protocol Reference & NSApplication Class Reference in the API doc (accessible via Xcode, just search for applicationWillBecomeActive).
Made the main viewcontroller class an AVAudioPlayerDelegate and used this code from Apple's "AddMusic" sample to make the audio alerts the app played mix nicely into the iPod audio etc...
I just dropped this code into a method that is called during viewDidLoad. If this interests you, you fall into the "who should read this doc" category for this: Audio Session Programming Guide
// Registers this class as the delegate of the audio session.
[[AVAudioSession sharedInstance] setDelegate: self];
// The AmbientSound category allows application audio to mix with Media Player
// audio. The category also indicates that application audio should stop playing
// if the Ring/Siilent switch is set to "silent" or the screen locks.
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
I believe your application should run normally when suspended. (think Pandora Radio)
Check to see if your timer is being deallocated due to your view being hidden or some other event occurring.