Updating data in the background

Exclusive offer: get 50% off this eBook here
iOS Development with Xamarin Cookbook

iOS Development with Xamarin Cookbook — Save 50%

Over 100 exciting recipes to help you develop iOS applications with Xamarin with this book and ebook

€23.99    €12.00
by Dimitris Tavlikos | May 2014 | Cookbooks Open Source

In this article, written by Dimitris Tavlikos, the author of iOS Development with Xamarin Cookbook, we will learn how to make use of iOS 7's background fetch feature. This feature automatically wakes up the app at system-managed intervals, giving it a specific amount of time to retrieve data and update the UI.

(For more resources related to this topic, see here.)

Getting ready

Create a new Single View Application in Xamarin Studio and name it BackgroundFetchApp. Add a label to the controller.

How to do it...

Perform the following steps:

  1. We need access to the label from outside of the scope of the BackgroundFetchAppViewController class, so create a public property for it as follows:

    public UILabel LabelStatus { get { return this.lblStatus; } }

  2. Open the Info.plist file and under the Source tab, add the UIBackgroundModes key (Required background modes) with the string value, fetch. The following screenshot shows you the editor after it has been set:

  3. In the FinishedLaunching method of the AppDelegate class, enter the following line:

    UIApplication.SharedApplication.SetMinimumBackgroundFetchIn
    terval(UIApplication.BackgroundFetchIntervalMinimum);

  4. Enter the following code, again, in the AppDelegate class:

    private int updateCount;
    public override void PerformFetch (UIApplication application,
    Action<UIBackgroundFetchResult> completionHandler)
    {
    try {
    HttpWebRequest request = WebRequest.Create
    ("http://software.tavlikos.com") as HttpWebRequest;
    using (StreamReader sr = new StreamReader
    (request.GetResponse().GetResponseStream())) {
    Console.WriteLine("Received response: {0}",
    sr.ReadToEnd());
    }
    this.viewController.LabelStatus.Text =
    string.Format("Update count: {0}/n{1}",
    ++updateCount, DateTime.Now);
    completionHandler(UIBackgroundFetchResult.NewData);
    } catch {
    this.viewController.LabelStatus.Text =
    string.Format("Update {0} failed at {1}!",
    ++updateCount, DateTime.Now);
    completionHandler(UIBackgroundFetchResult.Failed);
    }
    }

  5. Compile and run the app on the simulator or on the device. Press the home button (or Command + Shift + H) to move the app to the background and wait for an output. This might take a while, though.

How it works...

The UIBackgroundModes key with the fetch value enables the background fetch functionality for our app. Without setting it, the app will not wake up in the background.

After setting the key in Info.plist, we override the PerformFetch method in the AppDelegate class, as follows:

public override void PerformFetch (UIApplication application, Action<UIBackgroundFetchResult> completionHandler)

This method is called whenever the system wakes up the app. Inside this method, we can connect to a server and retrieve the data we need. An important thing to note here is that we do not have to use iOS-specific APIs to connect to a server. In this example, a simple HttpWebRequest method is used to fetch the contents of this blog: http://software.tavlikos.com.

After we have received the data we need, we must call the callback that is passed to the method, as follows:

completionHandler(UIBackgroundFetchResult.NewData);

We also need to pass the result of the fetch. In this example, we pass UIBackgroundFetchResult.NewData if the update is successful and UIBackgroundFetchResult.Failed if an exception occurs.

If we do not call the callback in the specified amount of time, the app will be terminated. Furthermore, it might get fewer opportunities to fetch the data in the future.

Lastly, to make sure that everything works correctly, we have to set the interval at which the app will be woken up, as follows:

UIApplication.SharedApplication.SetMinimumBackgroundFetchInterval(
UIApplication.BackgroundFetchIntervalMinimum);

The default interval is UIApplication.BackgroundFetchIntervalNever, so if we do not set an interval, the background fetch will never be triggered.

There's more

Except for the functionality we added in this project, the background fetch is completely managed by the system. The interval we set is merely an indication and the only guarantee we have is that it will not be triggered sooner than the interval. In general, the system monitors the usage of all apps and will make sure to trigger the background fetch according to how often the apps are used.

Apart from the predefined values, we can pass whatever value we want in seconds.

UI updates

We can update the UI in the PerformFetch method. iOS allows this so that the app's screenshot is updated while the app is in the background. However, note that we need to keep UI updates to the absolute minimum.

Summary

Thus, this article covered the things to keep in mind to make use of iOS 7's background fetch feature.

Resources for Article:


Further resources on this subject:


iOS Development with Xamarin Cookbook Over 100 exciting recipes to help you develop iOS applications with Xamarin with this book and ebook
Published: May 2014
eBook Price: €23.99
Book Price: €39.99
See more
Select your format and quantity:

About the Author :


Dimitris Tavlikos

Dimitris Tavlikos is a freelance software developer living in Greece. With over 10 years of professional experience as a programmer, he specializes in mobile development with clients all over the world. Dimitris has a passion for programming, and has recently been awarded the Xamarin MVP designation for his work. He has written a book on iOS development and various articles on his blog.

Books From Packt


iOS Development using MonoTouch Cookbook
iOS Development using MonoTouch Cookbook

RubyMotion iOS Development Essentials
RubyMotion iOS Development Essentials

Xcode 4 iOS Development Beginner's Guide
Xcode 4 iOS Development Beginner's Guide

Application Development in iOS 7
Application Development in iOS 7

Flash iOS Apps Cookbook
Flash iOS Apps Cookbook

Unity iOS Game Development Beginners Guide
Unity iOS Game Development Beginners Guide

iOS 5 Essentials
iOS 5 Essentials

Core Data iOS Essentials
Core Data iOS Essentials


Code Download and Errata
Packt Anytime, Anywhere
Register Books
Print Upgrades
eBook Downloads
Video Support
Contact Us
Awards Voting Nominations Previous Winners
Judges Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software
Resources
Open Source CMS Hall Of Fame CMS Most Promising Open Source Project Open Source E-Commerce Applications Open Source JavaScript Library Open Source Graphics Software