I want to check whether my app was launched for background fetch in my application delegate's didFinishLaunchingWithOptions. There is nothing in launchOptions dictionary. So is there any way to check it?
I know that I can check applicationState
, but for some reason sometimes it returns UIApplicationStateBackground, even if I launch app normally.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if (application.applicationState != UIApplicationStateBackground) {
// Analytics initialization code
}
}
I've created breakpoint at Analytics initialization code and sometimes it enters to this block even if I launch app normally!
I know that I can detect the state later when applicationDidBecomeActive
or applicationDidEnterBackground
will be called. If I will use these approach to detect the state I need to move my Analytics initialization code to some other place. If it remain in application:didFinishLaunchingWithOptions:
it will be called every time when my app starts background fetch. So maybe I should just move Analytics initialization code to some other method and don't check applicationState
in application:didFinishLaunchingWithOptions:
? If so which method I can use for this?
The Background Fetching will NOT happen in your app after the user has killed it in the multitasking UI. This is by design.
You need to enable Background Mode in your project settings under capabilities tab. Under background modes you will find a few modes that satisfy various purposes of running an app in background.
The background Fetch API allows an app to get updated content when the app isn't running in the foreground. iOS intelligently schedules the background fetch events based on your app usage so when you open your app the content is always up to date.
Take a look at slides 19-21 of this presentation: http://www.slideshare.net/moliver816/background-fetch
Immediately upon launch, you can check if applicationState
equals UIApplicationStateBackground
in order to determine whether your app was launched into the background.
Otherwise, if you just want to know when your app is fetching data for background app refresh, you can do so inside the UIApplicationDelegate
method application:performFetchWithCompletionHandler:
.
You can wrap you analytics initialization code in a singleton using GCD dispatch once. That way you know it only runs one time per application load. Resume from background or any other states won't matter since the lifecycle is still continuous.
+ (Analytics*)sharedInstance
{
static dispatch_once_t onceToken;
static Analytics* sharedInstance;
dispatch_once(& onceToken, ^{
sharedInstance = [[self alloc] init];
//Do analytics initialization code here
});
return sharedInstance;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With