how to start to play music in locked screen in iPhone - iphone

I am using UILocalNotification to alert the user if app not running and MPMusicPlayerController to play iPod music and MPMoviePlayerController to play radio stream url.
According to Apple doc:
if iphone is locked and device receives local notification then it will play 30 second sound and when user slides the slider then it will take app in foreground and two scenarios take place
If App not running then calls method
(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
If App already running then calls method -
(void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)notify
and i can perform my task in these methods.
Problem :
I need my application to be able to play my sound (it may be iPod music or stream url but not local notification sound for 30 sec) when the iPhone is locked and local notification received and app is running in foreground.
Reference App :
"Alarm Clock HD" and other apps also available in app store are working fine in this way but these are not able to play alarm when app is running in background (i could not understand why???)
I also tried how-to-prevent-iphone-from-deep-sleeping :
which prevent the iPhone from deep sleep by playing silent music periodically but how to notify app that notification has received so start to play "actual music" ? And how to start to play new music?

#manju sorry i got late but it work for you.
selectedDate = [timePicker date];
it is selectedDate date object,at this time your notification will came.
[NSDate date] by this you can find current time. and find different both time via.
NSTimeInterval timeDifference = [ selectedDate timeIntervalSinceDate:[NSDate date]];
Now when your are schedule your notification then .write this code
UIApplication *app = [UIApplication sharedApplication];
UIBackgroundTaskIdentifier bgTask = 0;
NSTimer *backgroundTimer = [NSTimer scheduledTimerWithTimeInterval:timeDifference target:self selector:#selector(backgroundTask) userInfo:nil repeats:NO];
bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
}];
-(void)backgroundTask
{
NSLog(#"Here you can play song via player ");
}
Don't forgot to add in app.infolist
UIApplication BackgroundMode Audio
it will solve your problem , play song when device is lock.

use AVAudioSessionCategoryPlayback for audio session. Check audio session programming guide here

Related

Network disconnect issue when iOS screen locks

In iOS 5 When Application Enter background wi-fi connection is lost.
But I want to use wi-fi connection for the next 4-5 minutes before the device sleeps as some tasks can be performed within 4-5 minutes of application enter background.
I think this can be accomplished by using beginBackgroundTaskWithExpirationHandler:, but i am not able to solve the problem
just disable iPhone to go to sleep mode
-(void) sleepModeDisable{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}
call this function every 10 second, this might help u
The way I handle this is to use beginBackgroundTaskWithExpirationHandler for every network request I'm sending.
This way I make sure that all my networking will completed even if my app moved to background.
I'm usually using one singleton object to handle all network request, so before the request is sent I call
- (void)startBackgroundTask
{
// ask for extra time if this is called when app go to suspended
UIApplication *application = [UIApplication sharedApplication];
_bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// Clean up any unfinished task business by marking where you.
// stopped or ending the task outright.
[application endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}];
}
And after I get a response (success/failure) or if I canceled the request, I call
- (void)stopBackgroudTask
{
UIApplication *app = [UIApplication sharedApplication];
if (_bgTask != UIBackgroundTaskInvalid) {
[app endBackgroundTask:_bgTask];
_bgTask = UIBackgroundTaskInvalid;
}
}
* Don't forget to define UIBackgroundTaskIdentifier *_bgTask;
Also if you are planning to make a massive use of Wi-Fi you should set the Application uses Wi-Fi key in your plist file to YES, otherwise your Wi-Fi will be shut done after 30 minutes even if your app is running.
No rocket science here, this is intended behavior in iOS that to save battery the Wi-Fi shuts off when phone is locked UNLESS you tell iOS that your app needs a persistant Wi-Fi, then it wont close it for you when your app is running.
For that just add UIRequiresPersistentWiFi to your info.plist and mark it YES
Documentation

How to run command NSLog(#"Alert display...") immidiately when alert Local Notifications show?

How to run command NSLog(#"Alert display...") immidiately when alert Local Notifications show?...I'm creating a alarm clock in iphone, I want to play a music at that time (at alert Local Notifications display)! I'm going to use AVPlayer to play music form ipod library in iphone! But I can't do it. Can you help me! Thanks!
You can't execute your code when LocalNotification pops up if your app is in background and suspended. What you can do is assign you music file to soundName property, but note that your sound must not be longer then 30 secs. Here is the code:
UILocalNotification* localNotification = [[UILocalNotification alloc] init];
localNotification.soundName = #"yourMusicFile.caf";
Of course, if your app isn't suspended you can play music using AVAudioPlayer...

issue With NSTIMER iOS SDK

i wrote like:
[NSTimer scheduledTimerWithTimeInterval:900 target:self selector:#selector(CallGetCounts) userInfo:nil repeats:YES];
that means i want to repeat my timer for every 5 mins but my timer is not repeating, not able to find the reason
can any one please tell me the answer.
I wrote this in "AppDelegate" -> "- (void)applicationDidEnterBackground:(UIApplication *)application" method.
In background your code is suspended and no timer events you will receive until your application comes to the foreground again.
You should go for scheduled local notifications to get waken up from background after a given interval. However they will show a popup or a banner to the user that he has to accept first.
Here are some steps on how to do it:
// When you want to schedule:
UILocalNotification* localNotification = [[[UILocalNotification alloc] init] autorelease];
localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5]; // seconds
localNotification.timeZone = [NSTimeZone defaultTimeZone];
localNotification.alertBody = #"Body text";
localNotification.alertAction = #"Button text";
[[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
// when it's fired it will call your AppDelegate's didReceiveLocalNotification
- (void)application:(UIApplication *)app didReceiveLocalNotification:(UILocalNotification *)localNotification
{
// you can handle timer event here and eventually re-schedule your local notification
}
Normally when an app enters the background, it is suspended so it doesn't execute at all. In particular, NSTimers don't fire. If you want something to happen in the background, you need to configure your app to run in the background and use one of the approved methods of performing the task you want to do. running NSTimers is not one of the supported tasks.
I suggest you review the iOS Programming Guide and particularly the Background Execution and Multitasking section.
The instance of UILocalNotification fires the pop up box(and waken up your app) whenever it triggered as per the time you set, If you really chosen the UILocalNotification then Here are the good tutorial links discussed in S.O thread. Hope those will help you.

iPhone AVPlayer - Execute Code in Background

I am trying to stream a remote mp3 using AVPlayer.
I have set up the Audio Session, and added the Plays Audio In Background to my info.plist file.
I am running this code:
self.timeObserver = [self->player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:nil usingBlock:^(CMTime time) {
[self updateControls];
}];
to add a time observer, that calls updateControls every second.
Thing is, when the sound buffer is low, the player just pauses, and this code in the background is stopped, so I have to manually press play in the app again. (and if I pause the player, this code doesn't run either)
Am I doing anything wrong? How can I run a piece of code the whole time in the background without interruptions?
You can't run arbitrary code in the background indefinitely. You can keep the audio playing, but you shouldn't be expecting to update your UI if you're not the frontmost app. You can update the UI when your app moves back into the foreground.
As long as you set your AVAudioSession properly and make it active, and you have the UIBackgroundModes set, you should be good to go on the audio front.
see http://developer.apple.com/library/iOS/#documentation/Audio/Conceptual/AudioSessionProgrammingGuide/Configuration/Configuration.html
You will need to envelope your background code like this:
__block UIBackgroundTaskIdentifier bgTask = nil;
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^(void) {
[[UIApplication sharedApplication] endBackgroundTask: bgTask];
bgTask = UIBackgroundTaskInvalid;
}];
//Your bg code here
[[UIApplication sharedApplication] endBackgroundTask: bgTask];
bgTask = UIBackgroundTaskInvalid;

Is it possible to stop the sound of a UILocalNotification from playing when the notification is delivered?

If a UILocalNotification fires with a sound set, and the user taps "Cancel" on the notification alert, the sound is stopped. But if the user taps "View", iOS then delivers the notification to the app and the sound keeps on playing. Is there any way to cancel this sound from the app? Canceling the notification in the app once the notification is delivered doesn't work (I didn't expect it to, the notification has already been delivered after all), and since I don't have the sound's system sound ID (and I didn't allocate it in the first place), I can't call AudioServicesDisposeSystemSoundID (can I?).
Is it possible to stop a UILocalNotification sound from playing if the user taps the Action button of the notification's alert?
It does not stop on the device too (5.1)
I have been trying to fix it but I can't figure it out.
I actually got it to stop on the simulator using this
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
UILocalNotification *localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif) {
[[UIApplication sharedApplication] cancelLocalNotification:localNotif];
}
return YES;
}
but It still doesn't stop on the device
Apparently the problem only exists on the simulator (iOS 4.2 sdk), not on the actual device.
It can be handled in application delegate method as follows, if the user taps the Action button of the notification's alert, then the following method will be called, there we can cancel the notification
- (void)application:(UIApplication *)app
didReceiveLocalNotification:(UILocalNotification *)notif {
[[UIApplication sharedApplication]cancelLocalNotification:notif];
}
I had the same problem when initially testing with an iPhone 4.
The problem appears to have gone away as of iOS 8 and now Local Notification Sounds stop when canceled after transitioning to the App.
iPhone4 [ iOS - 7.1.2 ] - Local Notification sound keeps playing in App no matter what
iPhone6 [ iOS - 8.1.1 ] - Local Notification sound stop when canceled programmatically
From what I can infer, it appears a fix exists somewhere in iOS 8.x
(Alas I didn't manage to find any documentation or release notes on the matter.)
The Problem becomes a non-issue for apps focusing on iOS 8
(provided you cancel the Local Notification coming in)