Keep iphone active while running program - iphone

how to set iPhone device to stay active ( to not lock ) while my app is running ?
Any idea

I'm not sure if this prevents the device from locking, but you can prevent the screen from dimming with the UIApplication's idleTimerDisabled property:
[UIApplication sharedApplication].idleTimerDisabled = YES;
From the documentation:
Important: You should set this property only if necessary and should be sure to reset it to NO when the need no longer exists. Most applications should let the system turn off the screen when the idle timer elapses. This includes audio applications. With appropriate use of Audio Session Services, playback and recording proceed uninterrupted when the screen turns off. The only applications that should disable the idle timer are mapping applications, games, or similar programs with sporadic user interaction.

This code will prevent your iPhone from going to sleep while your app is running
// avoid sleeping when this application is running
UIApplication *application = [UIApplication sharedApplication];
application.idleTimerDisabled = YES;
// Or simpler
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];

If you landed here looking for an answer in Swift, it's this:
UIApplication.sharedApplication().idleTimerDisabled = true
for Swift 3
UIApplication.shared.isIdleTimerDisabled = true
The warning in this comment still applies.

Related

How to turn Auto-Lock to Never in Swift?

Is there any Swift command to actually set the Auto-Lock to Never or a specific time period? I want to create a simple app that only has two buttons: one is to set the Auto-Lock to Never and the other one is to set it back to iOS default (1 min).
So when a user open this app and tap the Never button, s/he can open other apps but the iPhone or iPad will never auto lock while running the other apps. If s/he is done with other apps, s/he can open this app again and tap the Default button to set the Auto-Lock back to 1 min.
I understand this can be done from the Settings but I am just curious how I can do it from the backend using Swift.
I am new to Swift, btw.
Thanks much!
So when a user open this app and tap the Never button, s/he can open other apps but the iPhone or iPad will never auto lock while running the other apps
You can't do that. You are sandboxed. You cannot affect what happens to the user while running some other app.
When app is open, try to disable the idleTimer in viewDidLoad
UIApplication.shared.isIdleTimerDisabled = true
When app is closed to open other apps, try to -enable again idleTimer when yourViewController disappears, so put this in viewDidDisappear
UIApplication.shared.isIdleTimerDisabled = true
You need to make use of this API call to set the idle timer disable and enable.
This is in objective-C. Just convert it to swift. The API is available in UIApplication.h
-(void) onApplicationDidActivate:(NSNotification*) notification
{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}
-(void) onApplicationWillDeactivate
{
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
}

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

Force app to close and run in background

we have an app that has a specific purpose where an exit is required. After the exit a process needs to run in the background for a certain amount of time or until finished. We just need to know how to programmatically force the app to enter the background where processes can continue running. Any help on this would be great! Thanks in advance!
UPDATE: We have confirmed that there does not seem to be a programmatic way to force the app to quit / enter background and continue running background tasks. You can force the the app to exit using exit(0); but this kills the app all together. However, the bulk of this question was concerning running tasks in the background. We have found a solution that allows our app to begin processing data and handling tasks that a user has setup to be processed. Here is the code required. This needs to be added to the app delegate and multitasking is required on the device / IOS.
- (void)applicationDidEnterBackground:(UIApplication *)app{
// Check that IOS supports multitasking
if ([[UIDevice currentDevice] respondsToSelector:#selector(isMultitaskingSupported)]){
// Check that the device supports multitasking
if ([[UIDevice currentDevice] isMultitaskingSupported]) {
// Custom setting to allow users the freedom to enable or disable background tasks
BOOL enabled = [[NSUserDefaults standardUserDefaults] boolForKey:#"backgroundTasksEnabled_key"];
if ( enabled ){
//Get the shared application instance
backGroundApp = [UIApplication sharedApplication];
background_task = [backGroundApp beginBackgroundTaskWithExpirationHandler: ^ {
[backGroundApp endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;
}];
// Run in background
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSLog(#"\n\nProcess background tasks!\n\n");
// Do your work here
});
}
}
}
}
You can force an iOS app into the background by sending a registered URL to another app to handle, such as a web site URL to Safari.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString: myWebsiteURL ]];
Many many apps that call Safari to handle URLs are approved by Apple.
To get any time in the background, an app has to be appropriately configured using one of the allowed background modes (audio, location or VOIP); or the app can request a few minutes of extra time in the background before being suspended by calling the beginBackgroundTaskWithExpirationHandler method
You can't have a process running (doing work) in the background in iOS, you get a few seconds when the app quits to do any clean up and that's it!
You cannot force an application into the background, I'm fairly sure that Apple's guidelines prohibit you from doing that. What could your app possibly be doing that it can only do in the background and not in the foreground?

How do I keep the user's iPhone's display on?

So, I was looking for a way to keep the user's iPhone display on for a clock app. I found [UIApplication sharedApplication].idleTimerDisabled = YES; but that keeps the device from locking all of the time. I tried to [UIApplication sharedApplication].idleTimerDisabled = NO; when the application goes into the background, but that doesn't work. How can I safely keep the user's device from sleeping while my app is running?
Alter the idleTimerDisabled property whenever your app changes its active state - if you're going to be backgrounded, re-enable the timer, and when you regain control, disable the timer again.
Here's my solution, using XCode 6.2.
iPhone - phone goes to sleep even if idleTimerDisabled is YES
Basically, even now, in 2015, the only way to safely make sure that the device doesn't go to sleep is to repeatedly call a piece of code to keep the device awake.
-(void)callEveryTwentySeconds
{
// DON'T let the device go to sleep during our sync
[[UIApplication sharedApplication] setIdleTimerDisabled:NO];
[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
}

How to stop MPMusicPlayerController from enabling screen locking

I have an application that requires the iPhone screen to remain active (or not, depending on user choice). I've done this by disabling the application idle timer, which works fine and dandy until I start playing media via the MPMusicPlayerController. Due to a bug in the SDK, this then reenables the idle timer with no apparent way to disable it again.
My app flow is:
App starts
Screen stays on
<...time passes...>
Play audio file
Idle timer kicks in
Screen turns off
I have an empty audio file playing in the background to stop the phone going into deep sleep, but I'd really like to keep the screen unlocked too.
Has anyone managed to figure out a workaround for this?
I had a similiar problem, and found a fix for it. The fix might work for you too:
I call a method periodically (every 10 seconds), which sets idleTimerDisabled first to NO, then to YES.
- (void)calledEveryTenSeconds
{
[UIApplication sharedApplication].idleTimerDisabled = NO;
[UIApplication sharedApplication].idleTimerDisabled = YES;
}
Only setting to YES alone does not fix the problem. It seems the property has to change first to be recognized by UIApplication.
My problem was, that the screen kept turning dark as soon as I switched music tracks on the iPod player via the headphone remote. My guess is, that this is the same issue as you are experiencing.
You should simply turn off the idle timer. What I usually do in a viewcontroller that needs to stay 'awake' is this:
- (void) viewWillAppear:(BOOL)animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled: YES];
}
- (void) viewWillDisappear: (BOOL) animated
{
[[UIApplication sharedApplication] setIdleTimerDisabled: NO];
}
This will make sure the screen will not get locked due to user inactivity.
I found a solution to this problem. Invoke a method that disables the idleTimer in about 5 seconds after you start playing the music. It's a bit of a hack, but it is a workaround.
[[SoundEngine mainEngine] playMusic];
[self performSelector:#selector(setIdleTimeDisabled) withObject:nil afterDelay:5.0];
- (void) setIdleTimeDisabled {
[UIApplication sharedApplication].idleTimerDisabled = YES;
NSLog(#"Setting idleTimer to TRUE");}
let player = MPMusicPlayerController.applicationMusicPlayer()
player.setQueueWithStoreIDs(["some id"])
player.play()
player.pause()