iPhone/iOS: Best practices to shorten launch time of an app? - iphone

I found it took 4-5 seconds on an iPhone4/iOS6.0 device, and I want to know what is the system doing in that time, are there any best practices to short the launch time of an app?
many thanks.
EDIT:
I log it and it took about 1.5s in applicationDidFinishLaunchingWithoptions:
,and it is like 3.5-4s(I used a clock to get a preciser time) from I tap the app icon to its launch screen disappear.That is to say, about 2-2.5s to launch the app before calling applicationDidFinishLaunchingWithoptions

Simply watch Session 225 Up and Running: Making a Great Impression with Every Launch from WWDC 2012, it will take you through the process of profiling your app launch and give tips on most often made mistakes, it's great.

There is a very very good WWDC 2012 video with a long sequence devoted to exactly this topic: Session 235 (Responsiveness). I strongly recommend that you watch it. It gives you lots of hints and tricks for speeding up launch (don't link to too many libraries, etc.), tells you how to measure and how to read your measurements in Instruments, etc.

The system isn't what's causing your app to take 4-5 seconds to launch. It's probably your code in applicationDidFinishLaunching, or the init, viewDidLoad, or other setup methods of your root view controller.
Profile your app on a real device with the 'Time Profiler' Instrument. Only launch your app, don't press any buttons on the UI once it's launched. We only want to see what's going on during launch.
I would suggest checking the 'Separate by Thread,' 'Invert Call Tree,' 'Hide System Libraries,' and 'Show Obj-C Only' options under 'Call Tree' on the lower left side of the window.
Once you've checked your chosen options, go down the list of method calls. Start with the ones taking the most time (for obvious reasons). You can double click on symbol names to get more detailed information on where time was spent. Good luck!

We had the same problem.
Ultimately, we sped up launch time significantly by preloading the video in viewDidAppear. By the time the user taps the play button to launch the movie, enough content has loaded so that it can begin playback almost immediately.
e.g.:
- (void)viewDidAppear:(BOOL)animated {
NSURL *movieURL = [NSURL URLWithString:#"http://static.example.com/movie.mov"];
MPMoviePlayerViewController *vc = [[MPMoviePlayerViewController alloc] initWithContentURL:movieURL];
vc.moviePlayer.shouldAutoplay = NO;
[vc.moviePlayer prepareToPlay];
self.moviePlayerViewController = vc;
}
Full details in this blog post: http://blog.tetherpad.com/blog/2013/3/22/improving-tutorial-movie-load-times-on-ios-for-fun-and-profit

In my opinion, the launch time mainly cost in function,
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
If you do a bunch of stuff which blocks process, it will take long for launch.
So you can optimise your applicationDidFinishLaunching by moving out some unnecessary code which you can do later. Or you can make your code non-block, for example, you should use asynchronous network requests in applicationDidFinishLaunching instead of synchronous ones.

Related

Keeping an app alive in background unlimited (for a Cydia app)

I don't mind using private API's or anything of the kind that Apple doesn't like, but would prefer a quick solution that doesn't stuff like playing silence in the background or swizzling.
Obviously this isn't for the app store so please no lecturing :)
So how do you run in the background without any restrictions like "backgrounder"? I didn't manage to find an answer besides some that point people to different directions, but maybe since then someone managed to dig it up already.
Update:
This solution no longer appears to be sufficient (~ iOS 7+ or 7.1+). I'm leaving the original answer for historical reference, and in case it helps produce a future solution based on this obsolete one:
It depends on what you mean by app. If you're talking about a non-graphical background service, then what you want is a Launch Daemon. See here for how to create a launch daemon.
If you have a normal UI application, but when the user presses the home button, you want it to stay awake in the background for an unlimited time, then you can use some undocumented Background Modes in your app's Info.plist file:
<key>UIBackgroundModes</key>
<array>
<string>continuous</string>
<string>unboundedTaskCompletion</string>
</array>
Then, when iOS is ready to put your app into the background (e.g. user presses home button), you can do this, in your app delegate:
#property (nonatomic, assign) UIBackgroundTaskIdentifier bgTask;
- (void)applicationDidEnterBackground:(UIApplication *)application {
// Delay execution of my block for 15 minutes.
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 15 * 60 * NSEC_PER_SEC), dispatch_get_current_queue(), ^{
NSLog(#"I'm still alive!");
});
self.bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
// should never get here under normal circumstances
[application endBackgroundTask: self.bgTask];
self.bgTask = UIBackgroundTaskInvalid;
NSLog(#"I'm going away now ....");
}];
}
Normally, iOS only gives you up to 10 minutes for your UI application to work in the background. With the undocumented background mode, you'll be able to keep alive past that 10 minute limit.
Note: this does not require hooking with MobileSubstrate. If you're using the second method (undocumented Background Modes), then it does require installing your app in /Applications/, not in the normal sandbox area (/var/mobile/Applications/).
Depending on what your "app" is going to do, you can hook MobileSubstrate. This will load with SpringBoard and essentially run "in the background".
If you want to write an actual application, then you can also write a "Dynamic Library" which will be loaded with SpringBoard by MobileSUbstrate. You can talk back and forth between this dylib and your app by using NSNotificationCenter; creating and posting notifications.

How to trigger a delegate method after a certain period of time?

I'm using a class which downloads a file asynchronously .. works a bit like this
// in AViewController.m
DataGetter *blueFile = [[DataGetter alloc] init];
blueFile.delegate = self;
[blueFile getData:#"http://example.com/blue-file"];
It has a delegate method which does stuff to the file once downloaded
- (void) dataGetterFinished:(DataGetter *)dataGetter
{
// code
}
This works OK in ideal conditions, but as we're dealing with a mobile device, connections are not always reliable. The connection might break off half way thru, or it might be unusably slow.
So I'm wondering how I would set up a delegate method which triggers after, say, 10 seconds, which then displays an error and stops the operation. Would I have to use NSTimer, or NSNotification , or some combination?
Quinn "The Eskimo!" from Apple did a two talks on network programming for iPhone at WWDC 2010. It's session 207 and 208, you can download them here: http://developer.apple.com/videos/wwdc/2010/
The simple recepie for network success is:
Use NSURLConnection asynchronously.
Do not set a manual time-out using timers or any other means, the defaults are sane.
Instead be prepared to handle for a connection:didFailWithError:, that will be sent for time-outs.
If needed you can manually cancel a connection using -[NSURLConnection cancel], in response to user action for example.

Intermittent freezing on iPad

I have an iPad application that builds and runs perfectly the first time. But if I exit the application and open it again, the interface is completely unresponsive. If I exit and open another time, it never gets past the splash screen.
What's strange is that if I wait a minute or two before opening it again, it always runs fine.
Any ideas on what might be going on or where I should start my debugging efforts? I would throw in breakpoints and see what's going on, but by the time I start the application a second time, the debugger has already exited. Is there a way to keep the debugger and console running through multiple executions of an app?
Thanks,
Luke
Edit: Here's some code I use for NSUserDefaults - could this be the problem?
In viewDidLoad in my main view controller:
bgnum = [prefs integerForKey:#"bgnum"];
menuVisible = [prefs boolForKey:#"menuVisible"];
songTitles = [[NSMutableArray alloc] initWithArray:[prefs arrayForKey:#"songTitles"]];
numberOfSongs = [prefs integerForKey:#"numberOfSongs"];
In viewWillDisappear:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setBool:menuVisible forKey:#"menuVisible"];
[prefs setInteger:bgnum forKey:#"bgnum"];
[prefs setObject:songTitles forKey:#"songTitles"];
[prefs setInteger:numberOfSongs forKey:#"numberOfSongs"];
[prefs synchronize];
I'd look at what's happening in your initialization code, loadView, didFinishLaunching, etc., and trace it out. It's easy to get 3 or 4 methods deep in that stuff and do too much there when some of it should be lazy. With out more information or any sample code it's all wild guesses. One such guess is user defaults or anything that you're loading from a file or dictionary up front? I could see how something there could cycle through several states.
There's a big difference between "exiting the application and opening it again" which in context implies you are doing it rather quickly and "waiting a minute or two".
I have a rather large application that I develop on which routinely takes several seconds to "unload" on the iPad, which results in me rapidly exiting and re-entering causing the application to appear in a partially configured state, and causing unusual behavior.
This could be due to the fact that your application hasn't completely dealloc'd and closed its threads out, and thus when you launch it again quickly, the thread is resumed (and on 3.2 or earlier, will be unstable since it's already started killing itself off).
Do some timings... see what the threshold is for "it crashes" and "it works". If it's more than 10 seconds, then I would say something is wrong. Less than that, and you could be seeing what I just described,
With the device connected, run the app in debug mode from xCode and then exit the app. Now, disconnect the USB cable and run your app again - is it completely frozen? If you rotate the device, does your view orientation change? Once the app is terminated, plug your USB back in and go to xCode->Window->Organizer.
You should see your iPad device on the left of the screen. Select it and you should see some tabs on the right for Console and Crash report. Select your app from the dropdown and look to see if any console messages have been logged, or if a crash has occured - you should get a stack trace if it did which should help.
I once had a similar problem when I had NSZombieEnabled as an active argument in my executable, so that could be worth investigating too.

idleTimerDisabled not working since iPhone 3.0

I have used:
[UIApplication sharedApplication].idleTimerDisabled = YES;
in a number of Apps developed and running under iPhone OS 2.x and never had any problems with it. They were clock apps so needed to run constantly and ignore the iPhone's idle Timer setting.
However, trying to achieve the same with a new App running OS 3.0 (and which needs to be deployed under 3.0 as it uses some 3.0 APIs) I've found the idle Timer to be either ignored or inconsistent.
My App plays music from the iPod library and when the music is playing it auto-locks regardless of the above setting. But once you unlock it, it then doesn't auto-lock again unless you play music again, in which case it locks again after the iPhone auto-lock time setting.
I'm amazed no-one else has come across this as I imagine it would affect a large number of Apps.
Just to clarify:
1. The above code is in ApplicationDidFinishLaunching
2. I know that the phone won't auto-lock when testing from xCode regardless of settings
If anyone has any thoughts I'd be very grateful...
Our app uses the MPMediaPLayer. We also had the idleTimerDisabled=YES code in the ApplicationFinishedLaunching, which works EXCEPT if untethered, and there is already a current nowPlayingItem which is left playing (or unpaused, if paused at app startup). Obviously this is all with the Settings -> General -> Autolock set to some timed value.
By adding idleTimerDisabled=NO, immedately followed by idleTimerDisabled=YES in one of the other bits of code AFTER we had figured out what bit of music we would get playing seemed to solve the problem. Just setting it to YES was insufficient.. and subsequent queries had always indicated the correct value (YES).. so it appears the Apple code ignores the setting of the value IF there is a current piece of music and that is not changed by your code.. but does notice a change of value.
This is all under iOS 3.0.
Even in 2015, using iOS 8.2, this bug is still alive and kicking.
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];
}
Sounds like a bug, file with Radar - I am not too surprised this has not been seen much as there are probably not a lot of apps that try to lock the screen open and play music.
Having same issue. It does work when the device is plugged in. You can press lock button on top, and my NSTimer fires later and causes a vibrate. However if the device is not plugged in pressing the lock button puts the device to sleep. Any solution would be greatly appreciated.
iCodeblog posted about the idletimer, I said it didn't work, and the person who develops 'cute clock' was nice enough to reply. You have to do a hack, play a 1 second or longer silent sound every 10 or so seconds with NSTimer. This keeps the device awake even if the user hits the lock button.
I develop Seconds - Interval Timer for iPhone and iPod touch and I've had no end of trouble with this. The idea of my app is that people create timers based on a number of intervals where each interval can have it's own playlist or track played.
In iOS3 I had the problem that I couldn't disable the idle timer by just setting idleTimerDisabled = YES. In the end I came up with the same solution as Neil whereby I would periodically set it to NO, then immediately to YES again. This seemed to work.
I'm now updating the app to iOS4 (I know, iOS5 is just around the corner...) and now I have the opposite problem. If the MPMediaPlayer changes track before the idle timer reaches it's limit it gets reset. I've just tested this by creating an interval in my app that was 55 seconds, my auto-lock was set to a minute. At 50 seconds the screen dimmed as it prepared to lock, but at 55 seconds when the music changed it went back to full brightness and then didn't lock as it should.
Overall, the implementation of this seems flakey at best.

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.