Using “BackgroundFetch” in iOS to do task in the Background.

By | March 5, 2016

Hi Friends,

Here is a simple way to do background task in iOS using “BackgroundFetch”.

We will just try to send a message to the UI when a new data arrives in the background.
You can do anything there you want.

To enable “BackgroundFetch” in your app, you have to do some modifications in your project.

Go to App->Capabilities->Background Modes and enable “Background Fetch” as shown in the image below.

Background Fetch iOS

Now that we have enabled “BackgroundFetch”…we will now do some modifications in the code.

Go to your AppDelegate.

 
func applicationDidEnterBackground(application: UIApplication) {

	print("applicationDidEnterBackground")

	UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum);

}

func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {

	print("Background fetch called...");

	completionHandler (UIBackgroundFetchResult.NewData)

	NSNotificationCenter.defaultCenter().postNotificationName(NOTIFICATION_ID, object: nil)
	
	return

}

 

Our ViewController will look like this..
It will wait for the data to arrive and receive notification.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
       
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "newDataArrived:", name:NOTIFICATION_ID, object: nil)
    }

    func newDataArrived(notification: NSNotification)
    {
        print("New Data Arrived..Refresh the UI");
    }


}

Now Hit Home button, you will get a call to “performFetchWithCompletionHandler” at about 10 mins from now, although its not documented by apple to be 10 minutes, In iOS 6 in practice it took that much time.

Or you can trigger it by Xcode Menu -> Debug -> Background App Refresh after moving to background.

Install it in your device and try.

You can download the complete Source Code from here.

Leave a Reply

Your email address will not be published. Required fields are marked *