iOS Background Fetch example

iOS 7 provides multitasking API to fetch/download the content regularly in background. Using iOS background fetch API, your App can register with the system and get callback to download the content in background.
iOS Background Fetch Source Download


1). You need add UIBackgroundModes key with the fetch value in your app’s Info.plist fileiOS Background Fetch

 Info.plist source contains:


2). You need to implement application:performFetchWithCompletionHandler in app delegate

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler

		//Tell the system that you ar done.


How to initialize:

	[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:minimumBackgroundFetchInterval];

If minimumBackgroundFetchInterval is UIApplicationBackgroundFetchIntervalMinimum, then system will decide when to call performFetchWithCompletionHandler method.
If minimumBackgroundFetchInterval is UIApplicationBackgroundFetchIntervalNever, then system will never call callback handler.
This API is not like a timer task, system will decide when to call the handler depending on many if you set timeInterval to 2.00f( 2secs), handler is called for every 2+(minimum 2)secs.


When performFetchWithCompletionHandler method is called, app has up to 30 seconds of time to perform the download operation and call the specified completion handler block. If the completion handler is not called in time, then your app will be suspended.



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
return YES;

-(void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
NSLog(@"########### Received Background Fetch ###########");
//Download  the Content .




Testing Background fetch in Simulator?
You can test background fech in two methods.
1). Run your app in simulator. In XCode Menu, Go to “Debug” => “Simulate Background Fetch”.
after this performFetchWithCompletionHandler() is called.
Simulate Background Fetch


2). In XCode Menu, Go to “Product” => “Scheme” => “Edit Scheme”
enable the option “Background Fetch“. Rebuild and Run you app. performFetchWithCompletionHandler() is called while launching the app

Simulate Background Fetch while launching