This tutorial will teach you how to use Background Fetch, a multitasking API provided with the iOS 7 SDK. To do so, we'll create a simple list of delicious dishes that are automatically fetched in the background. Read on!
Project Overview
Background Fetch is an awesome feature released with iOS 7. Today, we live in a social world, and most of our users have several social network apps on their mobile devices. However, every time the user opens each app, they typically must wait until the app updates to view more recent content. This can be painful if several apps and profiles are used. Now, with background fetch, all content can be automatically fetched and updated before the user loads the app.
The default Traffic application is a simple example of how Background Fetch works in action. If you check it every morning, let's say at 8:20 AM, your iOS app must get that information at that time. Now, if the operating system knows you will access the app around 8:20 AM, it can fetch the data beforehand and have it ready when desired.
1. Project Setup
The first step is to create an iOS 7 project and choose single view app. Next let's add some properties which will be useful along the tutorial:
@property (nonatomic) NSMutableArray *objects; @property (nonatomic) NSArray *possibleTableData; @property (nonatomic) int numberOfnewPosts; @property (nonatomic) UIRefreshControl *refreshControl;
The NSMutablearray objects will be used to save the objects listed within the TableView. Note that, in this tutorial, you will not call any service to obtain data. Instead, you will use the possibleTableData array and randomly choose several objects from it. However, the app can easily be improved to fetch data from a server if you'd like.
The integer numberOfnewPosts represent the new posts that are available every time you will pull a request or receive a background fetch. The refrestControl is a control that is used when updating tasks. Since it is out of the tutorial context we will not cover it. However, you should look at this Mobiletuts+ tutorial if you'd like to learn more.
In the Main.storyboard, change the to a UITableViewController. Next, click on the UITableViewController and go to Editor > Embed in > Navigation Controller. Don't forget to set the Custom Class to .
Now, move to . the first step is to load some data. The following code will alloc and create the data object, create a title, and initialize the refreshControl:
self.possibleTableData = [NSArray arrayWithObjects:@"Spicy garlic Lime Chicken", @"Apple Crisp II", @"Eggplant Parmesan II", @"Pumpkin Ginger Cupcakes", @"Easy Lasagna", @"Puttanesca", @"Alfredo Sauce", nil]; self.navigationItem.title = @"Delicious Dishes"; self.refreshControl = [[UIRefreshControl alloc] init]; [self.refreshControl addTarget:self action:@selector(insertNewObject:) forControlEvents:UIControlEventValueChanged]; [self.tableView addSubview:self.refreshControl];